Oxnard
Oxnard

Reputation: 269

Angular 7 innerHTML using a material design button

Trying to create a Angular directive for password show/hide functionality. the show/hide works, however when trying to use a material design (mat) button it does not show the mat button it shows a default html button. In the directive I have

  toggle(span: HTMLElement) {
    this._shown = !this._shown;
    if (this._shown) {
      this.el.nativeElement.setAttribute('type', 'text');
      span.innerHTML = '<button mat-raised-button color="primary">Hide</button>';
    } else {
      this.el.nativeElement.setAttribute('type', 'password');
      span.innerHTML = '<button mat-raised-button color="primary">Show</button>';
    }
  }

in the app.component.html I do have some buttons working as a test so I do know mat is working.

<div>
  <button mat-raised-button>basic</button>
  <button mat-raised-button color="primary">primary</button>
</div>
<div>
  <label>Enter Password</label>
  <input type="password" appPassword>
</div>

My question is using a directive which uses the innerHTML how can I get material design buttons to work?

thanks

Upvotes: 0

Views: 1303

Answers (1)

Nadhir Falta
Nadhir Falta

Reputation: 5267

You don't have to use a directive for that, you can use Angular's native code to achieve that. something like this:

 <mat-form-field>
    <input matInput placeholder="Enter your password" [type]="hide ? 'password' : 'text'">
    <button mat-icon-button matSuffix (click)="hide = !hide" [attr.aria-label]="'Hide password'" [attr.aria-pressed]="hide">
    <mat-icon>{{hide ? 'visibility_off' : 'visibility'}}</mat-icon>
    </button>
  </mat-form-field>

Check Angular's doc for that:
https://material.angular.io/components/form-field/overview#prefix-amp-suffix

Upvotes: 0

Related Questions