簡體   English   中英

Angular2 - 無法動態更改輸入類型

[英]Angular2 - cannot change input type dynamically

我想知道是否有人可以幫助解釋為什么我無法動態更改表單輸入類型?

例如

<user-input type="{{ isActive ? 'password' : 'text' }}"></user-input>

不起作用。

但這有效,

<user-input type="password" *ngIf="isActive"></user-input>
<user-input type="text" *ngIf="!isActive"></user-input>

用戶input.ts

import { Component, Input } from '@angular/core';

@Component({
    selector: 'user-input',
    templateUrl: './user-input.html'
})
export class UserInput {

    @Input()
    public isActive: boolean;

    constructor() {

    }
}

用戶input.html

<input 
    type="{{ isActive ? 'password' : 'text' }}" 
    class="form-control"
    [(ngModel)]="value"
/>
user-input-password.ts

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector:
      'input[type=password][formControlName],input[type=password][formControl],input[type=password][ngModel]'
})
export class PasswordValueAccessor {

    public pattern: RegExp;

    private regexMap = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,16}$/;

    @HostListener('keypress', ['$event']) 
    public onKeyPress (e: any)
    {
        this.pattern = this.regexMap;
        const inputChar = e.key;

        if (this.pattern.test(inputChar)) {
            // success
        } else {
            e.preventDefault();
        }
    }
}

我遇到的問題是,當我動態設置類型時,不會觸發user-input-password指令。 如果我直接將類型設置為密碼,那么它會被觸發。

還有另一種動態改變輸入類型的方法嗎?

嘗試這個

<user-input [type]="isActive ? 'password' : 'text'"></user-input>

請看一下這個

動態生成角度為2的輸入字段類型並設置字段的類型

你可以這樣喜歡。 工作時間最多:

<user-input #input type="password" ></user-input>
<button (click)="changeInput(input)">Change input</button>

ts文件

changeInput(input: any): any {
    input.type = input.type === 'password' ? 'text' : 'password';
  }

我建議從打字稿中處理這個問題

type: string;

functiontochangetype(){
if(your condtion ){
this.type="password";
}else{
this.type="text"
}
}

並在HTML中

<user-input type={{type}}></user-input>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM