首页 > 解决方案 > 使用 Nativescript 显示/隐藏密码文本

问题描述

我想在我的登录表单中显示/隐藏密码文本。我有如下代码。

我试试这段代码:

    <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>

在 component.ts 我写了这段代码:

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";
        }
    }
}

当我单击显示 true false 中的函数toggleShow()console.log(this.show) ,但在模板中不显示任何内容。你能问我任何想法吗,我的代码有什么问题?

谢谢!

标签: angulartypescriptnativescriptshow-hideangular2-nativescript

解决方案


编辑:SeanStanden 发布了一个更好的解决方案,这应该是公认的答案。

就个人而言,我更喜欢secure使用元素引用来更改 Textfield 上的属性:

.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>

示例游乐场:https ://play.nativescript.org/?template=play-ng&id=Xmy1Pv&v=3


推荐阅读