动态插入 ng-content 选择

Posted

技术标签:

【中文标题】动态插入 ng-content 选择【英文标题】:Insert ng-content select dynamically 【发布时间】:2020-03-18 18:52:03 【问题描述】:

简单地说,我想将选择值作为输入传递给 ng-content 组件。它应该看起来像这样:

父母:

<child-component [selectedValue]="['[selectedhtml1]','[selectedHtml2]']">
  <div selectedHtml1>I'm inside!!</div>
  <div selectedHtml2>I'm inside also!!</div>
</child-component>

子-html:

<ng-content *ngFor="let value of selectedValue" select="value">

子-ts:

@Input() selectedValue: string[];

但是当我这样做时,我得到一个错误提示

compiler.js:2175 Uncaught Error: Template parse errors:
Can't bind to 'select' since it isn't a known property of 'ng-content'.
1. If 'select' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
    </mat-paginator>
  </div>
  <ng-content [ERROR ->]select="selectedValue"></ng-content>
</mat-card>
"): ng:///[path to my component]@[component line]
    at syntaxError (compiler.js:2175)
    at TemplateParser.parse (compiler.js:11388)
    at JitCompiler._parseTemplate (compiler.js:25961)
    at JitCompiler._compileTemplate (compiler.js:25949)
    at compiler.js:25893
    at Set.forEach (<anonymous>)
    at JitCompiler._compileComponents (compiler.js:25893)
    at compiler.js:25806
    at Object.then (compiler.js:2166)
    at JitCompiler._compileModuleAndComponents (compiler.js:25805)

用普通的嵌入语法来做这件事,为什么不这样做呢?

【问题讨论】:

试试看这个 - ***.com/questions/36755844/… 【参考方案1】:

在你的 html 中

<ng-content #select="selectedValue">

在.ts中

@ViewChild(select)

【讨论】:

但是你不能动态地制作 ViewChild 的可以吗?因此,如果我想为 ng-content 选择传入一个名称数组,然后 ngFor 通过该数组创建一个相邻列表,它将无法正常工作。 我已经编辑了 OP 以更紧密地匹配我正在做的事情。感谢您指出我的要求可以完成。 尝试使用 ViewChildren 而不是 ViewChild 用于多个属性:angular.io/api/core/ViewChildren#viewchildren 每次我的列表更改和我在父级的子组件标签之间放置的 html 更改时,是否需要我手动输入 ViewChildren? 我是否能够将类似数组的变量传递给组件以声明视图子级,或者我必须手动将其放入组件中以应对多个不同视图子级的情况?因为它可以工作,但它不会是动态的。

以上是关于动态插入 ng-content 选择的主要内容,如果未能解决你的问题,请参考以下文章

使用 ng-content 动态创建 angular2 组件

如何在 Angular 2 中编译 ng-content 中的动态模板

是否可以进行深度 ng-content 选择?

angular4:ng-content 基于嵌套类的选择

使用 ng-content 时在表单验证中不考虑输入

ng2中的ng-content用法