Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 将ng模板元素传递给指令_Angular_Typescript_Angular2 Template_Angular Directive - Fatal编程技术网

Angular 将ng模板元素传递给指令

Angular 将ng模板元素传递给指令,angular,typescript,angular2-template,angular-directive,Angular,Typescript,Angular2 Template,Angular Directive,我正在尝试将ng模板传递给我的指令,如下所示: component.html Lorem ipsum dolor sit amet. 指令.ts 从“@angular/core”导入{指令,输入} @指示({ 选择器:“[myDirective]” }) 导出类MyDirective{ @Input()myTemplate 恩戈尼尼特(){ log(this.myTemplate.elementRef.nativeElement) } } 但它只是显示。如何访问模板的内容?其他属性中似乎没

我正在尝试将
ng模板
传递给我的指令,如下所示:

component.html


Lorem ipsum dolor sit amet.

指令.ts

从“@angular/core”导入{指令,输入}
@指示({
选择器:“[myDirective]”
})
导出类MyDirective{
@Input()myTemplate
恩戈尼尼特(){
log(this.myTemplate.elementRef.nativeElement)
}
}
但它只是显示
。如何访问模板的内容?其他属性中似乎没有一个包含它-上的注释建议使用
templateRef
,但它未定义

如果需要的话

为了澄清,该指令的最终目标是有条件地将模板的内容添加到其父元素中(以及一些其他更改)。

如您所见:

ng模板是用于呈现HTML的角度元素。它从不直接显示。事实上,在渲染视图之前,Angular会用注释替换ng模板及其内容

所以在运行时,ng模板只是一个注释。它不能呈现为DOM,也不可能以ElementRef类型访问它

但是,如果您想向指令发送一个p元素,这是可能的。我更改了你的代码来实现这一点。请参阅此stackblitz项目:


您应该将其用作
*myTemplate
而不是
[myTemplate]
,这样结构指令就会收到您想要的内容。如果你想在里面使用一个模板,我建议使用@ContentChild或其他类型的模板。不作为其答案发布not@FranciscoSantorelli然后我得到“无法绑定到'myTemplate',因为它不是'div'的已知属性。”并且
@ContentChild
不符合我的要求,我希望模板可以重用,因此必须从指令外部访问。我不确定您试图实现什么。您是在尝试获取指令将注入的可重用模板(?),还是在尝试向指令传递一个可执行某些操作的模板?@FranciscoSantorelli指令的最终目标是有条件地将模板的内容添加到其父元素(以及其他一些更改)。我知道它适用于常规元素,但我需要使用模板,因为我不希望它在父组件中呈现。我可能不得不这样做,并使用CSS隐藏它或其他东西,如果没有办法用模板来做,但这并不理想。