首页 > 解决方案 > 如何在 Angular 6 中将数据从父组件绑定到可重用组件?

问题描述

我有一个侧边栏作为可重用组件,在ng-templateblogComponent 和 blogDeutilComponent 中使用。如何将数据从博客绑定到侧边栏?

堆栈闪电战

标签: angularangular6

解决方案


您可以在指令中通过 @Input() 以角度将数据传递给指令:

import { Directive, ViewContainerRef, OnInit , Input } from '@angular/core';
import { ReusableService } from './reusable.service';

@Directive({
    selector: '[reusableOutlet]'
})
export class ReusableDirective implements OnInit {

   @Input()
    set reusableOutlet(passedValue: any) {
        console.log(passedValue);
    }

    constructor(private viewContainerRef: ViewContainerRef, private reusableService: ReusableService) {}

    public ngOnInit(): void {
        this.reusableService.attach(this.viewContainerRef);
    }
}

用法:

<ng-template [reusableOutlet]="data"></ng-template>

演示


推荐阅读