Angular 4アプリケーションのコンポーネントで、次の簡単な例を考えてみましょう。 2つの入力フィールドを持つ単純なHTMLフォームを示しています。ネストされたコンポーネントを含むフォームで自動フォーム検証を実装する方法は?
今<input type="text" [required]="required" [(ngModel)]="model" (ngModelChange)="updateChanges()" />
次のHTMLで
import { Component, EventEmitter, Input, OnInit, Output } from "@angular/core";
@Component({
selector: "app-smart-input",
templateUrl: "./smart-input.component.html",
styleUrls: ["./smart-input.component.css"]
})
export class SmartInputComponent {
////////////////
// PROPERTIES //
////////////////
@Input() model: string;
@Output() modelChange: EventEmitter<string> = new EventEmitter<string>();
@Input("required") required: boolean = false;
/////////////
// METHODS //
/////////////
updateChanges() {
this.modelChange.emit(this.model);
}
}
:
<form #personForm="ngForm">
<input type="text" required name="firstname [(ngModel)]="firstname"/>
<app-smart-input required [(model)]="lastname"></app-smart-input>
<button [disabled]="personForm.valid === false">Send</button>
</form>
次のように子コンポーネントが定義されている:1つの入力フィールドが直接実装され、第二には、子コンポーネントの範囲内でありますモデルを完全に正常に更新する(firstname
とlastname
は期待通りにユーザー入力によって定義されます)。
私が達成したいのは、両方のフィールドが入力されない限り、ボタンが無効になることです。<input>
実装のrequired
フラグに注意してください。値はnull/undefinedであってはなりません。
残念ながら、firstname
が明確に定義されていない場合、ボタンは現在無効になっています。しかし、フォームはlastname
を気にしません。
これをどのように達成できますか?
注:Angular 2 creating reactive forms with nested componentsはsimularですが、私は反応型ではなくテンプレート駆動型を使用しています。しかし、それはおそらく何とか適応されることができますか?