首页 > 解决方案 > 无法访问 html 模板中的 this.text

问题描述

我正在尝试添加两个按钮,它们应该只显示输入字段中是否有一些文本,否则它应该默认隐藏/禁用,但我收到了这个错误。

<div class="card card-body">

`<form>`
    `<div class="form-group">`
        `<input type="text" class="form-control" placeholder="Add a Log ...">`
        `<input type="submit" value="Add Log" class="btn btn-light" [disabled]=!this.text>`
        `<button class="btn btn-warning" [hidden]=!this.text>Clear </button>`
    `</div>
`</form>

</div>

错误:清除~~~~~~~~~

         src/app/components/log-form/log-form.component.ts:5:16
         templateUrl: './log-form.component.html',
                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
       Error occurs in the template of component LogFormComponent.

标签: htmlangularbootstrap-4

解决方案


您可以使用 ngModel 轻松实现这一点,如下所示:

mycomp.component.html

<form>
 <div class="form-group">
     <input type="text" class="form-control" name="text" [(ngModel)]="textvalue" placeholder="Add a Log ...">
     <input type="submit" value="Add Log" class="btn btn-light" [disabled]="!textvalue">
     <button class="btn btn-warning" [hidden]="!textvalue">Clear </button>
 </div>
 {{textvalue}}//contains value of your input element.
</form>

mycomp.component.ts

export class MyComponent {
  textvalue:string;
}

确保在 app.module.ts 文件的 imports[] 数组中导入 FormsModule 以使 ngModel 工作。输入的名称属性也很重要,或者您可以使用 formControlName。

希望这可以帮助!!!


推荐阅读