Reputation:
I have Input in component:
@Input() applicant: Applicant;
interface Applicant {
applicant: ApplicantItem,
representative: Representative
}
Template is:
<div *ngIf="applicant.representative.type></div>
Problem is if applicant
has no object representative
it falls.
How to set default value if there is no representative
?
Like this:
@Input() applicant: Applicant = <Applicant>{};
I need to have representative
with type
always.
Also how to avoid error here:
applicant.representative = adapt(applicant.representative);
Here applicant.representative
should be default object { representative: {type:
}}`
Upvotes: 1
Views: 8653
Reputation: 5144
This is what I use to set a configuration object with defaults.
code
@Input('applicant') _applicant: {applicant?: ApplicantItem, representative?: Representative }
public get applicant(): {applicant: ApplicantItem, representative: Representative } {
const defaults = {
applicant: new ApplicantItem(),
representative: new Representative()
}
return {...defaults, ...this._applicant}
}
Upvotes: 0
Reputation: 11
When we use class then
@Input() applicant: Applicant = new Applicant();
When we use interface then:
@Input() applicant: Applicant = {} as Applicant;
Upvotes: 0
Reputation: 1242
Hai you can try to set the value in ngOnInit. once the ngOnInIt is called the value for the
applicant
will be set if any provided by the parent component.
Here check if the value is undefined and if so set a default
@Input() applicant: Applicant;
ngOnInIt() {
if (!this.applicant) {
this.applicant = {
// ur defaults here
};
}
if you want to always pass proper values to children components from parent then
this.applicants.map((applicant) => {
if (!applicant || !applicant.representative) {
applicant = {
// your defaults here
};
this.representativeAdapter.adapt(applicant.representative);
...
Upvotes: 1
Reputation: 451
You can do it by specifying setter and getter for your @Input:
@Input()
set applicant(applicant: Applicant) {
this._applicant = applicant || { applicant: null, representative: null };
}
get applicant(): Applicant {
return this._applicant;
}
private _applicant: Applicant;
Upvotes: 0
Reputation: 282
You can try this
@Input() applicant = function(applicant : Applicant = {applicant:null, representative:nul}){
console.log(applicant)
}
Upvotes: 0