Search code examples
angulartypescriptnativescriptshow-hideangular2-nativescript

show/hide password text using Nativescript


I want to show/hidden password text in my login form. I have a code like below.

I try this code:

    <GridLayout margin="10" verticalAlignment="center" backgroundColor="#ffffff">
        <StackLayout margin="10" verticalAlignment="center" [formGroup]="signUpForm" padding="15">
            <StackLayout class="input-field">
                <TextField formControlName="username" hint="Username"></TextField>
            </StackLayout>
            <StackLayout class="input-field">
                <TextField formControlName="password" hint="Password" secure="true">
                </TextField>
            </StackLayout>
            <Label text ="show/hide" (tap)="toggleShow()"></Label>
        </StackLayout>
   </GridLayout>

In component.ts I write this code:

export class LoginComponent implements OnInit {
    signUpForm: FormGroup;
    show = false;
    type=  'password';
    constructor(....) {
        this.signUpForm = this.formBuilder.group({
            username: ["", Validators.required],
            password: ["", Validators.required]
        });
    }
    toggleShow()
    {
        this.show = !this.show;
        if (this.show){
            this.type = "text";
        }
        else {
            this.type = "password";
        }
    }
}

When I click the function toggleShow() in console.log(this.show) show true false, but in template doesn't show nothing. Can you ask me any idea please, what is wrong in my code?

Thank you!


Solution

  • EDIT: SeanStanden posted a better solution, which should be the accepted answer.

    Personally, I'd prefer to alter the secure property on the Textfield using element references:

    .ts:

    export class HomeComponent {
        @ViewChild('passwordField') passwordField: ElementRef;
    
        constructor() { }
    
        toggleShow() {
            console.log(this.passwordField.nativeElement.secure);
            this.passwordField.nativeElement.secure = !this.passwordField.nativeElement.secure;
        }
    }
    

    .html:

    <GridLayout margin="10" verticalAlignment="center" backgroundColor="#ffffff">
        <StackLayout margin="10" verticalAlignment="center" padding="15">
            <StackLayout class="input-field">
                <TextField hint="Username"></TextField>
            </StackLayout>
            <StackLayout class="input-field">
                <TextField #passwordField hint="Password" secure="true">
                </TextField>
            </StackLayout>
            <Label text="show/hide" (tap)="toggleShow()"></Label>
        </StackLayout>
    </GridLayout>
    

    example playground: https://play.nativescript.org/?template=play-ng&id=Xmy1Pv&v=3