我有以下代码:
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { JobsService } from '../jobs.service';
@Component({
selector: 'job-post',
templateUrl: './create.template.html',
providers: [JobsService]
})
export class JobPostComponent {
job: any = {};
errorMessage: String;
constructor(private _router:Router, private _jobsService:JobsService) {}
create() {
this._jobsService
.create(this.job)
.subscribe(createdJob => this._router.navigate(['/jobs', createdJob._id]), error => this.errorMessage = error);
}
}
:
create.template.html
<h1>Post New Job</h1>
<form (ngSubmit)="create()" novalidate>
<div class="form-group">
<label for="isExtensible">Is Extensible</label>
<input type="checkbox" required [(ngModel)]="job.isExtensible" name="isExtensible" id="isExtensible">
</div>
<div class="form-group">
<label class="form-control-label" for="isOpenEnded">Open Ended</label>
<input type="checkbox" required [(ngModel)]="job.isOpenEnded" name="isOpenEnded" id="isOpenEnded">
</div>
<div class="form-group">
<contract-type></contract-type>
</div>
</form>
contract-type.component.ts
和bellow是另一个组件import { Component } from '@angular/core';
import { Http } from '@angular/http';
@Component({
selector: 'contract-type',
template: `
<div *ngIf="contractTypes">
<label class="form-control-label" for="contractType">Contract Type</label>
<select id="contractType" name="contractType" required [(ngModel)]="job.contractType" class="form-control">
<option value="0">Select an item</option>
<option *ngFor="let contractType of contractTypes" value="contractType.name_en">{{ contractType.name_en }}</option>
</select>
</div>
`
})
export class ContractTypeComponent {
private contractTypes;
constructor(private _http: Http) {
this._http.get('/api/contractTypes')
.subscribe(function(res){
this.contractTypes = res.json();
console.log(this.contractTypes)
});
}
}
*ngIf
,控制台是这样的:
但是在浏览器上它不是任何下拉列表,如果我从div中删除can not read property <contractTypes> of undefined
,则会显示错误create.template.html
。
故事是这样的,我需要一个从api响应填充的下拉列表,在table(cut(diamonds$price, breaks=seq(-500,20000,1000)))
内。
答案 0 :(得分:0)
在您的组件之间添加交互,如下所示: 在您的父组件内&#39; create.template.html&#39;:
<contract-type [job]="job"></contract-type>
并在conract-type.component.ts
内:
首先导入Input
:
从&#39; @ angular / core&#39;中导入{Component,Input};
然后将组件类更改为:
export class ContractTypeComponent {
private contractTypes;
@Input() job;
constructor(private _http: Http) {
this._http.get('/api/contractTypes')
.subscribe((res)=>{
this.contractTypes = res.json();
console.log(this.contractTypes)
});
}
}