Angular2 выбирает шаблон динамически в соответствии с ответом сервиса
У меня есть компонент под названием «Узел», который должен отображать одну запись, но у меня больше, чем тип записи, и у каждого типа есть свой вид (макет).
Таким образом, у этого компонента есть параметр ID, который будет использоваться для получения ответа от службы, а затем в соответствии с типом записи он должен отображать правильное расположение.
например:localhost/test_app/node/123
где 123 - это параметр id.
@Component({
selector: 'node',
directives: [Post, Project],
template: `
<post *ngIf="response.post.post_type == 'post'" content="response.post"></post>
<project *ngIf="response.post.post_type == 'project'" content="response.post"></project>
`,
})
export class Node{
id: number;
response: any;
constructor(private _param: RouteParams,
public service: Service
){
this.id = +_param.get('id');
}
ngOnInit(){
this.service.get(this.id).subscribe(
res=> this.response = res.json()
);
}
}
Подход 2: использование динамического загрузчика компонентов.@Component({
selector: 'node',
directives: [Post, Project],
template: '<div #container></div>'
})
export class Node{
id: number;
response: any;
constructor(private _param: RouteParams,
public service: Service,
private loader:DynamicComponentLoader,
private elementRef:ElementRef
){
this.id = +_param.get('id');
}
ngOnInit(){
this.service.get(this.id).subscribe(
res=> {
this.response = res.json();
this.renderTemplate();
}
);
}
renderTemplate(template) {
this.loader.loadIntoLocation(
this.getCorrectTemplate(),
this.elementRef,
'container'
)
}
getCorrectTemplate(){
if(this.response.post.post_type == "post"){
return '<post content="response.post"></post>';
}
else{
return '<project content="response.post"></project>';
}
}
}
Мне интересно, какой подход более эффективен или есть лучший подход, пожалуйста, поделитесь им.