作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我创建了一个用于处理选择框的组件,现在当我在提交表单后将其放入表单标签时,选择的结果不会显示在控制台中。
我的代码有什么问题?我该如何解决这个问题?
@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>
关于angular - 如何在表单内将 ngModel 与自定义控件一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41933819/
我是一名优秀的程序员,十分优秀!