選択されたラジオボタンに基づいてフォーム検証ツールを実行しようとしています。したがって、Instagramが選択されている場合は1つのバリデータが実行され、Facebookが選択されている場合は別のバリデータが実行されます。私のコンポーネントテンプレートは以下の通りです:条件付きフォーム検証ツールAngular2
<div class="form-group" [ngClass]="{ 'has-error' : !requestURL.valid && submitAttempt }">
<div class="radio">
<label for="instagram">
<input type="radio"
name="socialmedia"
id="instagram"
value="instagram"
[checked]="selectedSourceType === 'instagram'"
(click)="updateSelectedSourceType('instagram')">
<i class="fa fa-instagram"></i>
</label>
<label for="facebook">
<input type="radio"
name="socialmedia"
id="facebook"
value="facebook"
[checked]="selectedSourceType === 'facebook'"
(click)="updateSelectedSourceType('facebook')">
<i class="fa fa-facebook"></i>
</label>
</div>
<label for="requestSource">Submit URL</label>
<span *ngIf="requestURL.hasError('alreadyTracked')" class="already-following">Already Following This User</span>
<input type="text"
id="requestSource"
class="form-control"
placeholder="Enter a website, Facebook Page or Instagram handle"
ngControl="requestURL">
ようにselectedSourceTypeが切り替えられると、この値が実行されるバリを決定する必要があります。ただし、コンストラクタのために、実行時の元の値は、他のラジオボタンが選択されている場合でも、実行されるバリデータです。誰にもこれに対して可能な解決策がありますか?
theForm: ControlGroup;
requestURL: Control;
submitAttempt: boolean = false;
isLoading: boolean = false;
selectedSourceType:string = 'facebook';
validationUrls = {
instagram: 'post-ig-url?src=',
facebook: 'post-fb-url?src='
}
constructor(private _applicationService:AppService,
private _elRef:ElementRef,
private _router:Router,
private _http:Http,
private _builder:FormBuilder) {
super(_elRef, _applicationService, _router);
this.createRequestURLControl(CustomValidators.facebookURL);
this.theForm = _builder.group({
requestURL: this.requestURL
});
}
requestSource(form){
console.log('Selected source:', this.selectedSourceType);
this.isLoading = true;
this.submitAttempt = true;
let sub = this._http.post(this.validationUrls[this.selectedSourceType] + form.requestURL, '')
.subscribe(data => {
console.log("URL Submitted for review", data);
this.isLoading = false;
}, error => {
console.info(error.json().message);
});
this.addSubscription(sub);
}
createRequestURLControl(validator:any) {
this.requestURL = new Control('', Validators.compose([validator, Validators.required]));
}
updateSelectedSourceType(sourceType:string) {
this.selectedSourceType = sourceType;
// update validators
if (sourceType === 'facebook') {
this.createRequestURLControl(CustomValidators.facebookURL);
} else {
this.createRequestURLControl(CustomValidators.instagramURL);
}
// clear input
}
この方法論は素晴らしく効果的でした。 – ConorJohn