在角度组件之间共享@input

时间:2018-03-15 13:55:33

标签: angular

可以在两个角度组件之间共享数据,而其中一个组件在另一个组件中使用? 我使用以下代码来定义组件的模板,我想只指定一次“Source”属性。

是否可以从父组件继承导入? 因为我只会在“ui-grid”中使用“ui-grid-header”

对于这个项目,我是Angular版本5.2

因为我对Angular开发还很新。 有没有一个地方可以找到这样的信息?

模板

<ui-grid [source]="gridDatasource">
  <ng-template #headerTemplate let-data>
    <th>
        <ui-grid-header [source]="datasource" [sortColumn]="'Name'">
            Name
        </ui-grid-header>
    </th>
    <!-- Omitted rest of the code for example -->
  </ng-template>
</ui-grid>

UI-网格组分

@Component({
    selector: 'ui-grid',
    templateUrl: './grid.component.html'
})
export class GridComponent implements OnInit, AfterContentInit{
    @ContentChild('headerTemplate')
    headerTemplate: TemplateRef<any>;

    @Input("source")
    public datasource: AbstractGridDataSource;

    /* Omitted rest of the code for example */
}

UI-网格报头组分

@Component({
    selector: 'ui-grid-header',
    template:
`
<ng-container *ngIf="datasource">
    <a [ngClass]={disabled:!sortColumn} (click)="sortColumn && datasource.setOrderColumn(sortColumn)" href="javascript:void(0)">
        <ng-content></ng-content>
    </a>
</ng-container>
`
})
export class GridHeaderComponent {
    @Input("source")
    public datasource: AbstractGridDataSource;

    @Input("sortColumn")
    public sortColumn: string;
}

2 个答案:

答案 0 :(得分:1)

您可以做的是将source组件中的ui-grid-header传播到所有ui-grid-header子组件中,如下所示:

GridComponent中抓住子组件:

@ContentChildren(GridHeaderComponent) headers: QueryList<GridHeaderComponent>;

对于简单的一次性绑定,只需使用ngAfterContentInit传递值:

ngAfterContentInit() {
  this.headers.forEach(header => header.source = this.source);
}

如果您需要处理多次绑定,则需要使用ngOnChanges来检测source何时更改并将其传播到那里。

答案 1 :(得分:1)

通常使用共享服务解决此问题:

@Component({
    selector: 'ui-grid',
    templateUrl: './grid.component.html',
    providers: [SharedService]
})
constructor GridComponent(private service:SharedService)
//save input i.e. sharedService.set(input)
//------------------------------------------------
constructor GridHeaderComponent(private service:SharedService)
//get input i.e. sharedService.get()
相关问题