angular - 类型错误 : Cannot read property 'valid' of undefined

标签 angular

我有以下文本区域:

<textarea class="form-control" [(ngModel)]="content" name="content" required>
        </textarea>

和以下提交按钮:

 <button type="submit" class="btn btn-default" [disabled]="content.valid">New comment</button>

正如我在 Angular 2 表单指南 ( https://angular.io/docs/ts/latest/guide/forms.html ) 中看到的,我可以使用 x.valid 来检查它是否不为空。

为什么会出现 TypeError: Cannot read property 'valid' of undefined 错误?

最佳答案

在您的情况下,content 是您模型的一个属性。

为了做你想做的事,你需要使用 template reference value对于表单控件 #myControl="ngModel" 然后您可以访问有效属性:myControl.valid

所以在你的例子中:

<textarea class="form-control" [(ngModel)]="content"
          name="content" required #myControl="ngModel">
</textarea>

并在按钮标签中使用它:

<button type="submit" class="btn btn-default" 
[disabled]="myControl.valid">New comment</button>

关于angular - 类型错误 : Cannot read property 'valid' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39213386/

相关文章:

Angular 2+ 设置标准表单字段外观值

css - 如何隐藏带有嵌套选项卡组的 mat-tab-header,隐藏外部 mat-tab-group 而不隐藏内部

angular - 我们如何在 Angular 4 中获取 HttpClient 状态码

angular - 为什么自定义管道给出错误 : Property 'transform' in type 'EllipsisPipe' is not assignable to the same property in base type 'SlicePipe'

html - ngx-bootstrap:可使用模板排序(水平)

typescript - 如何从 Angular 2 中的日期类型中减去一年?

javascript - Angular 9 : Unable to redirect to a specific route in angular app after redirecting from an external url

angular - 如何在等待可观察对象从 Angular 中的服务获取数据时显示加载微调器

Angular 2,如何使用setTimeout?

angular - Vs Code nx 控制台生成命令不起作用 : This command has no flags to set