【问题标题】:Angular2 - Get component html before templateAngular2 - 在模板之前获取组件 html
【发布时间】:2016-03-09 19:31:31
【问题描述】:

我有 2 个这样定义的组件 A 和 B:

组件 A:

import { Component, CORE_DIRECTIVES, ElementRef} from 'angular2/angular2';
import ComponentB from ".'ComponentB";

@Component( {
    selector: 'component-a',
    directives: [ CORE_DIRECTIVES ],
    template: `
        <component-b>
            Inner text/html, whatever...
        </component-b>
    `
} )

export class ComponentA( {
    static parameters = [ [ ElementRef ] ];
    element:ElementRef;
    constructor( element:ElementRef ) {
        this.element = element;
    }

    afterViewInit():void {
    }
} )

组件 B:

import { Component, CORE_DIRECTIVES, ElementRef} from 'angular2/angular2';

@Component( {
    selector: 'component-b',
    directives: [ CORE_DIRECTIVES ],
    template: `
        <h1>{{innerContent}}</h1>
    `
} )

export class ComponentB( {
    static parameters = [ [ ElementRef ] ];
    element:ElementRef;
    innerContent:string;

    constructor( element:ElementRef ) {
        this.element = element;
    }

    afterViewInit():void {
    }
} )

我想要完成的是使用组件A模板中&lt;component-b&gt;标签之间的内容来设置组件B的变量innerContent

我尝试在 ComponentB 类的 afterViewInit 内使用 this.element.nativeElement.innerHTML,但它获取的是模板变量的 innerHTML,而不是父变量的。

限制: 使用@Inputs/@Outputs 在组件中使用自定义属性不是一种选择。 例如

    <component-b [innerContent]="Inner text/html, whatever...">
    </component-b>

【问题讨论】:

    标签: html typescript angular


    【解决方案1】:

    在 ComponentB 模板中,输入:

    template: `
        <h1><ng-content></ng-content></h1>
    `
    

    【讨论】:

      猜你喜欢
      • 2017-11-11
      • 2017-12-03
      • 1970-01-01
      • 1970-01-01
      • 2017-03-07
      • 1970-01-01
      • 2019-01-11
      • 2020-03-17
      • 2017-12-27
      相关资源
      最近更新 更多