私はいくつかの助けが必要です。ドロップダウン値をラップするカスタムコンポーネントを作成しようとしています。これは、必須かどうかに応じてデフォルトの - 選択 - オプションを表示/非表示にします。 (そして、後でこのコンポーネントに他のカスタムロジックを適用したい)Validatorにアクセスする方法カスタムコンポーネントの中に必要
Validator.requiredで私のカスタムコントロール内のどのように取得するのですか?
私は角に新たなんだけどないAngularJS
親ページのHTML:
<div formGroupName="siteType">
<my-dropdownlist
id="siteType"
formControlName="code"
[items]="arrayOfItems">
</my-dropdownlist>
</div>
親ページ.TS:
export class MyPage {
serviceForm: FormGroup = this.fb.group({
siteType: this.fb.group({
code: [serviceData.siteType, Validators.required]
})
});
カスタムコントロールのhtml:
の<select class="form-control" id="itemType">
<option *ngIf="!selectedValue && required">--Select--</option>
<option *ngFor="let item of items" [value]="item">
{{ item }}
</option>
</select>
カスタムコントロールTS:
import { Component, Input, Output, EventEmitter, forwardRef, OnInit} from '@angular/core';
import { NG_VALIDATORS, FormControl, Validator, NgForm, FormBuilder } from '@angular/forms';
@Component({
selector: 'my-dropdownlist',
templateUrl: './dropdownlist.component.html',
providers: [
{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => DropdownListComponent),
multi: true
}
]
})
export class MyDropdownListComponent implements Validator, OnInit {
@Input() items: any[];
@Input() required: boolean = false;
@Input() formControlName: string;
private selectedValue: any;
ngOnInit() {
//Some way to get at the Validator.required set on the parent form here so I can tell whether to apply it to my dropdown?
}
public validate(c: FormControl) {
return null; //TODO for additional future validation
}
}
デモ:http://plnkr.co/edit/AokYjOv0ZWD2XFVTWjEf?p=preview – Alex