问题
I'm working with Angular 2+ and Material 2. I have some md-button(s) which I want to change to md-raised-button dynamically. For example I want this:
<a md-button [routerLink]="['/home']">Home</a>
to change into this:
<a md-raised-button [routerLink]="['/home']">Home</a>
when the link is active or I'm hovering over it etc.
回答1:
according to this answer That is not supported.
but you can do this :
<a *ngIf="condition" md-button [routerLink]="['/home']"
(mouseover)="condition= true" (mouseout)="condition= false">Home</a>
<a *ngIf="!condition" md-raised-button [routerLink]="['/home']"
(mouseover)="condition= true" (mouseout)="condition= false" >Home</a>
回答2:
I'll do this like this
<a [attr.md-button]="!value ? true : null"
[attr.md-raised-button]="value ? true : null"
(mouseover)="value = true"
(mouseout)="value = false"
[routerLink]="['/home']">Home</a>
By default the value will equal to false so md-button attribute will be added and on hover md-raised-button will be added and md-button will be removed you can extend logic regarding your need.
回答3:
The focus on a button is very simple as below
<button md-raised-button (click)="button1.focus()">Focus on Raised
Button</button>
<button md-raised-button #button1>Raised button</button>
To change a md-button
to md-raised-button
you can use property binding as below
<a md-button routerLink="." [class.md-raised-button]="val">Flat button</a>
<button md-raised-button (click)="focus(button1)">Focus on Raised Button</button>
<button md-raised-button #button1>Raised button</button>
Typescript method will be as
export class ButtonDemo {
val:boolean=false;
focus(element){
element.focus();
this.val=true;
}
}
LIVE DEMO
来源:https://stackoverflow.com/questions/42605871/how-to-change-directive-dynamically-in-angular-2