選択ボックスを処理するためのコンポーネントを作成しましたが、フォームを送信した後にフォームタグに配置すると、選択の結果がコンソールに表示されません。
私のコードの問題は何ですか?どうすればこれを修正できますか?
@Input
。を付けてスローします。これが選択ボックスコンポーネントです:
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'input-select',
template:`
<div class="field-select">
<span><icon name="select-arrow" size="10"></icon></span>
<select name="{{name}}" class="field">
<option value="0" disabled selected>{{label}}</option>
<option *ngFor="let option of options" [ngValue]="option.value">{{option.name}}</option>
</select>
</div>
`
})
export class InputSelectComponent implements OnInit {
@Input() label: string;
@Input() name: string;
@Input() options;
// testOptions = [
// {value:'test',name:'test2'},
// {value:'test',name:'test2'}
// ];
constructor() { }
ngOnInit() {
console.log(this.options);
}
}
HTMLでの使用法:
<input-select label="test" name="select2" [options]="testOption"></input-select>
フォームhtml:
<form role="form" class="form" #f="ngForm" (ngSubmit)="onSubmit(f)">
<input class="field" name="name" ngModel type="text" placeholder="n1">
<input-select label="b2" name="select2" [options]="testObject"></input-select>
<input class="field" name="building-type" type="text" ngModel placeholder="b3">
</form>
コンソールログ:(選択ボックスの値はありません)
Object {name: "test", building-type: "tset" }
私は今あなたの問題を抱えていると思います。
ControlValueAccessor
カスタムコンポーネントに実装して、ngModel
!?を使用してフォーム内で使用します。
コンポーネントは次のようになります。
@Component({
selector: 'ng2-input-select',
template: `
<div class="field-select">
<select name="{{ name }}" class="field" [(ngModel)]="value" (ngModelChange)="_onChange($event)">
<option value="" disabled selected>{{ label }}</option>
<option *ngFor="let option of options" [value]="option.value">{{ option.name }}</option>
</select>
</div>
`,
providers: [
{ /* idk why or what this will do exactly.. but it works! ;) */
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => SelectBoxComponent),
multi: true
}
]
})
export class SelectBoxComponent implements OnInit, ControlValueAccessor {
@Input() label: string;
@Input() name: string;
@Input() options;
@Input() value: string = '';
// ControlValueAccessor implementation
// ====================================
// call if value was changed inside our component
private _onChange = (_: any) => { };
// call if input was "touched" .. !
private _onTouched = () => { };
// incoming change..
public writeValue(val: any) {
this.value = val;
}
public registerOnChange(fn: (_: any) => void): void { this._onChange = fn; }
public registerOnTouched(fn: () => void): void { this._onTouched = fn; }
}
ライブデモ:https://plnkr.co/edit/imCJmCoJaeGQiUMcyBwz?p = Preview
更新
フォームコンポーネントで変更検出を使用する:
<ng2-input-select ngModel (ngModelChange)="selectBoxChanged($event)" label="b2" name="select2" [options]="testObject"></ng2-input-select>
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加