I have the following code: post.component.ts
:
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>
and bellow is another component contract-type.component.ts
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)
});
}
}
and the console is like this: But on browser it is not any dropdown, and if i remove *ngIf
from div it shows an error can not read property <contractTypes> of undefined
. And story is like this, that i need a dropdown list that populated from api response, inside the create.template.html
.
Add interaction between your components like this: inside your parent component 'create.template.html':
<contract-type [job]="job"></contract-type>
and inside your conract-type.component.ts
: first import Input
: import { Component, Input} from '@angular/core'; Then change your component class to this:
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)
});
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.