首页 > 解决方案 > 将纯文本传递给 Angular 组件,在 typescript 级别访问 ng-content 值

问题描述

我有一个简单的组件:

@Component({
    selector: 'app-my-component',
    template: ``,
})
export class MyComponent {
    content: string;
}

Hello World当我像这样使用我的组件时,我希望 content 属性是:

<app-my-component>Hello World</app-my-component>

我怎样才能让它发生?

标签: angulartypescript

解决方案


您需要使用 Content projection (ng-content) 来显示父组件给出的文本并注入 ElementRef 以获取 typescript 文件中的值。

我的组件.component.ts

import { AfterViewInit, Component, ElementRef } from '@angular/core';

@Component({
    selector: 'my-component',
    templateUrl: './my-component.component.html',
    styleUrls: ['./my-component.component.scss'],
})
export class MyComponentComponent implements AfterViewInit {

    content: string;

    constructor(private elt: ElementRef) {
    }

    ngAfterViewInit() {
        this.content = this.elt.nativeElement.childNodes[0].nodeValue;
        console.log("content:", this.content);
    }
}

我的组件.component.html

<ng-content></ng-content>

父组件.component.html

<my-component>My text</my-component>

编辑:@Input如果您将内容投影到ng-container.


推荐阅读