Reputation: 534
I have an object in which all properties need to be passed to the child-component. Passing them one by one was too slow.
Is there a similar approach in Angular to how it can be done in React?
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-demo',
template: `
<p>
{{name}}-{{age}}
</p>
`
})
export class DemoComponent {
@Input() name: string = '';
@Input() age: number = 0
}
import { Component } from '@angular/core';
@Component({
selector: 'app-use',
template: `
<p>
use works!
</p>
<!-- Syntax similar to React, Pass in all at once, not one by one -->
<app-demo ...demoInject></app-demo>
`,
styleUrls: ['./use.component.css']
})
export class UseComponent {
demoInject = {
name: 'tom',
age: 20
}
}
Upvotes: 1
Views: 51
Reputation: 4525
In Angular you typically pass objects from the parent- to the child-component like this:
First the parent-component:
@Component({
selector: 'app-use',
template: `
<p>
use works!
</p>
<!-- Syntax similar to React, Pass in all at once, not one by one -->
<app-demo [demoDto]="demoInject"></app-demo>
`,
})
export class UseComponent {
demoInject = {
name: 'tom',
age: 20
} as DemoDto;
}
Then the child-component:
@Component({
selector: 'app-demo',
template: `
<p *ngIf="demoDto">
{{demoDto.name}}-{{demoDto.age}}
</p>
`
})
export class DemoComponent {
@Input()
demoDto!: DemoDto;
}
Upvotes: 1