![](/img/trans.png)
[英]How to pass arguments to other components while we reusing them in Angular 7
[英]How to pass objects to other components in Angular 9
我正在使用 Angular 9 和 Spring 引導,我正在創建案例模塊的一部分,為此我需要獲取一些數據來填充 select 輸入,微服務正常工作,它從數據庫獲取數據,但試圖呈現 select 輸入時它無法識別該變量。
這是 add-case.ts 的 oninit
ngOnInit(): void {
this.loading = true;
this.isLoading.add(
this.caseService.createCasesFork().subscribe(
data => {
this.casesFork = data;
this.grupos = this.casesFork.groups;
this.productos = this.casesFork.products;
this.tipologias = this.casesFork.tipologies;
this.intenciones = this.casesFork.intentions;
this.regiones = this.casesFork.regions;
this.loading = false;
console.log(this.casesFork.groups);
},
(error: HttpErrorResponse) => {
this.alert.errorIzi(error.message);
}
),
{key: 'loading'}
)
}
到目前為止它正在工作,它顯示了該組。
問題是我想在其中創建 select 輸入的表單組件,因為此表單是一個組件。
這是我試過的。
<select formControlName="grupos">
<option [value]="grupo" *ngFor="let grupo of grupos">
{{ grupo.name }}
</option>
</select>
但我得到這個錯誤
這是表單組件ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Action } from '../../../models/enums';
@Component({
selector: 'app-cases-form',
templateUrl: './cases-form.component.html',
styleUrls: ['./cases-form.component.scss']
})
export class CasesFormComponent implements OnInit {
@Input() action: Action;
@Output() submitForm = new EventEmitter<boolean>();
form: FormGroup;
methods = Action;
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
this.createForm();
}
createForm(): void {
this.form = this.fb.group({
grupos: ['', Validators.required],
name: ['', Validators.required],
field: ['', Validators.required]
});
}
onSubmit(): void {
if (this.form.valid) {
this.submitForm.emit(true);
}
}
}
我如何讀取模板或表單 ts 中的屬性? 歡迎任何幫助或建議,謝謝
首先,錯誤說明了原因。 您尚未在組件中定義grupos變量,因此它會拋出錯誤。
假設 add-case.ts 文件是可注入服務,您必須將其導入 CasesFormComponent 並且您可以在前端使用該服務,例如:
<select formControlName="grupos">
<option [value]="grupo" *ngFor="let grupo of addCaseService.grupos">
{{ grupo.name }}
</option>
</select>
或者您可以使用組件中的方法從 addCaseService 獲取組信息。
讓我知道是否有幫助。 謝謝
您應該在 CasesFormComponent 的輸入中獲取您的組的數據
@Input grupos :Grupos[] = [];
然后上HTML碼
<select formControlName="groups">
<option [value]="grupo" *ngFor="let group of grupos">
{{ grupo.name }}
</option>
</select>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.