How to Change Directive Dynamically in Angular 2

一世执手 提交于 2019-12-23 19:22:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!