【发布时间】:2019-04-16 12:03:09
【问题描述】:
我正在使用 Angular 6 开发一个 Web 应用程序。我想创建一些受 HTML 输入组件启发的自定义组件。例如:
CustomComponent.ts(打字稿)
@Component({
selector: 'custom-component',
templateUrl: './custom-component.html',
providers: [
{
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: forwardRef(() => InputTextComponent)
}
]
})
export class CustomComponent {
@Input() name: string;
@Input() isRequired: boolean;
}
CustomComponent.html(模板)
<input type="text"
[attr.name]="name"
[required] = "isRequired"
/>
我有这个问题。假设我们在这个模板中使用我的组件:
<form #myForm="ngForm" ngNativeValidate>
<custom-component
name="myName"
[isRequired] = true
ngModel
></custom-component>
<button type="submit" (click)="method()">Click</button>
required 属性在<input type="text/>(<custom-component> 的包装组件)中正确初始化。问题是这样的(这是一个 Angular 问题!):在这个使用代码中:
method() {
console.log(this.myForm.valid);
}
对象myForm.valid(其中myForm 与上一个模板中的#myForm 相关联)始终返回true 值,即使在文本字段中没有输入任何内容。这种行为是错误的:如果我不在必填字段中插入任何内容,我希望此值为 false。
【问题讨论】:
标签: html angular forms components