首页 > 解决方案 > 模板标签内容为空

问题描述

我正在尝试template在 Angular 组件中使用标签。

MDN 示例之后,我创建了一个类似的stackblitz 示例

在原始示例中,template标签没有子级,但它的内容有子级。在我的例子中,情况正好相反。模板有孩子,内容为空(打开控制台并单击按钮查看)。

结果,尝试操作克隆的模板内容失败。

我究竟做错了什么?


app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  click() {
    const template: HTMLTemplateElement = document.querySelector('#t');
    console.log(`template.childElementCount: ${template.childElementCount}`);
    console.log(`template.content.childElementCount: ${template.content.childElementCount}`);
    const content = document.importNode(template.content, true);
    console.log(content.querySelector('.c2'));
  }
}

app.component.html

<button (click)="click()">test</button>
<template id="t">
    <div class="c1">
        <div class="c2">{{ name }}</div>
    </div>
</template>

控制台结果

在此处输入图像描述

标签: htmlangular

解决方案


您应该只调用template而不是template.content作为第一个参数。

const content = document.importNode(template, true);
console.log(content.querySelector('.c2'));

在此处输入图像描述


推荐阅读