简体   繁体   English

如何使用 Angular 7 动态禁用输入

[英]How to disable an input dynamically with Angular 7

I'm trying to disable an input depending on the value taken from the Component.ts我正在尝试根据取自 Component.ts 的值禁用输入

In my component.ts file I have this value在我的component.ts文件中,我有这个值

disName = false;

And in my HTML I have these elements在我的 HTML 我有这些元素

Name: <input type="text"
             value="name"
             size="15"
             id="name"
             name="firstName"
             [(ngModel)]="aproverFirstName"
             [attr.disable]="disName=='true' ? true : null">

What looking for is that if my value on the component.ts is false, then in the html file the input element should change to disable depending on the value.寻找的是,如果我在component.ts上的值为 false,那么在 html 文件中,输入元素应根据值更改为禁用。

I've also tried this [disable]="disName"我也试过这个[disable]="disName"

I'm using Angular 7, thanks a lot!我正在使用 Angular 7,非常感谢!

The attribute you're looking for is [disabled].您要查找的属性是 [disabled]。

<input type="text" [disabled]="true" />

You should do like this:你应该这样做:

<input type="text"
             value="name"
             size="15"
             id="name"
             name="firstName"
             [(ngModel)]="aproverFirstName"
             [disabled]="disName">

But, I prefer to use @angular/forms in Angular, Then you can init the form like this:但是,我更喜欢在 Angular 中使用@angular/forms ,然后你可以像这样初始化表单:

HTML: HTML:

<input type="text"
                 value="name"
                 size="15"
                 id="name"
                 formControlName="firstName">

Typescript: Typescript:

Init form:初始化形式:

this.sampleForm= this.fb.group({
      firstName: [{ value: '', disabled: true }, Validators.required]
});

Control enable and disable by:通过以下方式控制启用和禁用:

this.sampleForm.controls.firstName.enable();
this.sampleForm.controls.firstName.disable();

Try this尝试这个

  <input type="text" [disabled]="!disName">

the condition has to be true.条件必须为真。

Are you putting this "input" tag in component.html?您是否将这个“输入”标签放在 component.html 中?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM