我创建了一个简单的可重用组件:
- 技术支助**
import {Component, Input, OnInit} from '@angular/core';
import {FormControl} from '@angular/forms';
@Component({
selector: 'app-select',
templateUrl: './select.component.html',
styleUrls: ['./select.component.css']
})
export class SelectComponent implements OnInit {
@Input() control: FormControl;
@Input() label: string;
@Input() options: [];
@Input() idAndForAttributes: string;
@Input() customClass: string;
constructor() { }
ngOnInit() {
}
}
- 超文本标记语言**
<div class="form-group" [ngClass]="{'invalid': control.invalid && control.touched && control.dirty}">
<label [attr.for]="idAndForAttributes">{{ label }}:</label>
<select class="form-control" [ngClass]="customClass" [formControl]="control" [attr.id]="idAndForAttributes">
<option value="0">- Select -</option>
<option *ngFor="let item of options" [ngValue]="item.id">{{item.description}}</option>
</select>
<ng-container *ngIf="control.dirty && control.touched && control.invalid">
<div *ngIf="control.errors.required || (control.errors.min && control.value == 0)">
<small style="color: #c62828;">
Value is required.
</small>
</div>
</ng-container>
</div>
现在我尝试在我的其他html中使用它:
<form [formGroup]="profileActivityForm">
<app-select [control]="profileActivityForm.get('activityType')" [idAndForAttributes]="'type'" [label]="'Type'"
[options]="profileActivityTypes"></app-select>
</form>
然后在TS中
profileActivityTypes: string[] = [];
ngOnInit() {
this.profileActivityTypes.push('New')
this.profileActivityTypes.push('Update')
this.profileActivityForm = this.fb.group({
activityType: [0]
});
}
但它显示了不可见的选项,如下图所示:
我认为问题出在可重用组件<option *ngFor="let item of options" [ngValue]="item.id">{{item.description}}</option>
的html上
因为它正在寻找一个描述,我怎样才能从子组件中将项目作为描述发送呢?
- 更新**
我试过:
profileActivityTypes: [] = [];
....
let profileActivities = [{ description: 'New' }, { description: 'Update' }]
this.profileActivityTypes.push(profileActivities)
但是它在push时抛出了一个错误:
类型为"{description:string ;}[]"不能赋给类型为" never "的参数
1条答案
按热度按时间eivgtgni1#
为了解决这个问题,我改变了
profileActivities
数组的赋值,而不是创建数组然后推送它。希望这对更多的人有效!