how to hide/show html tag in type script in Angular component

Viewed 80

I have created a form in angular Html component, which is used to add users and update them using dialog module. If the user clicks for updating, I want to hide password input in HTML.

    <mat-form-field appearance="outline">
        <mat-label>Password</mat-label>
        <input formControlName="password" matInput/>  
    </mat-form-field> 

enter image description here

2 Answers

You can use *ngIf directive to show/hide content. Basically, it accepts an expression. When the expression evaluates to true it shows the DOM, otherwise, it removes it from DOM. Over here you can control the behavior using isUpdating boolean.

<mat-form-field appearance="outline" *ngIf="isUpdating">
    <mat-label>Mot de passe</mat-label>
    <input formControlName="password" matInput/>  
</mat-form-field> 

I feel that for this use case, rather than hiding the field. You can disable the field until it is updating the password field. By show/hide field would introduce a flicker effect on UI (and that would be annoying for user)

<mat-form-field appearance="outline" *ngIf="isUpdating">
    <mat-label>Mot de passe</mat-label>
    <input formControlName="password" matInput [disabled]="isUpdating"/>  
</mat-form-field> 

After disabling the field. You can not retrieve password field from FormGroup object. You can get that using form.getRawValue() method instead of form.value method.

component.html

<ng-container *ngIf='!isUpdating'>
    <mat-form-field appearance="outline">
        <mat-label>Mot de passe</mat-label>
        <input formControlName="password" matInput/>  
    </mat-form-field>
</ng-container>

component.ts

export class Component {
    isUpdating = false;

    onUpdate() {
        this.isUpdating = true;
    }
}

You can add condition on Password Input Whenever isUpdating will set to true then password input will removed from DOM and If isUpdating will set to false then Password input will add in DOM automatically.

Related