показать / скрыть текст пароля с помощью 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";
        }
    }
}

Когда я нажимаю функцию toggleShow() в console.log(this.show), показываю true false, но в шаблоне ничего не отображается. Вы можете спросить меня, пожалуйста, что не так в моем коде?

Спасибо!


person Community    schedule 17.08.2018    source источник


Ответы (4)


РЕДАКТИРОВАТЬ: SeanStanden опубликовал лучшее решение, которое должно быть принятым ответом.

Лично я бы предпочел изменить свойство secure в текстовом поле, используя ссылки на элементы:

.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

person Brian Lin    schedule 17.08.2018
comment
Ах да, я только что увидел ваше решение ниже. Я согласен, это гораздо более элегантное решение. - person Brian Lin; 29.01.2019

Нет причин для доступа к собственному элементу. Вы можете привязать к свойству 'secure' и переключить, например:

<StackLayout class="input-field">
   <TextField formControlName="password" hint="Password" [secure]="securePassword">
   </TextField>
</StackLayout>
<Label text ="show/hide" (tap)="toggleShow()"></Label>

TS

toggleShow() {
  this.securePassword = !this.securePassword;
}
person SeanStanden    schedule 24.01.2019

Расширение ответа Шона специально для NativeScript-Vue, если кто-то его ищет.

<TextField class="input" :text="password" :secure="securePassword" ></TextField>

<Label class="passmsg" :text="passmsg" @tap="toggleShow()"></Label>

В методах:

toggleShow () {
  this.securePassword = !this.securePassword
  if (this.securePassword) this.passmsg = 'Show Password'
  else this.passmsg = 'Hide Password'
}

Добавьте passmsg в свой раздел данных

person SanVed    schedule 31.07.2019

Измените свой код, как показано ниже.

<StackLayout class="input-field">
    <TextField formControlName="password" [hint]="passwordType" secure="true"></TextField>
</StackLayout>

TS:-

passwordType: string = "password";
toggleShow()
    {
        this.passwordType = (this.passwordType == "password") ? "text" : "password";
    }

Надеюсь это поможет.

person Anji    schedule 17.08.2018