` }) export class AppCardComponent {}

使用:


  
    
      

Angular

    
  
  One framework. Mobile & desktop.   

由于 ng-container 的存在,header 部分并没有被渲染到我们想要渲染的插槽中,而是渲染到了没有提供任何 selectorng-content 中。
在这种情况下,我们可以使用 ngProjectAs 属性。
在上面的 ng-container 加上这个属性,就可以按照我们的期望来渲染了。


  
    
      

Angular

    
     One framework. Mobile & desktop.   

二、 有条件的内容投影

如果你的元件需要有条件地渲染内容或多次渲染内容,则应配置该元件以接受一个 ng-template 元素,其中包含要有条件渲染的内容。

在这种情况下,不建议使用 ng-content 元素,因为只要元件的使用者提供了内容,即使该元件从未定义 ng-content 元素或该 ng-content 元素位于 ngIf 语句的内部,该内容也总会被初始化。

使用 ng-template 元素,你可以让元件根据你想要的任何条件显式渲染内容,并可以进行多次渲染。在显式渲染 ng-template 元素之前,Angular 不会初始化该元素的内容。

2.1 ng-container

既不是一个组件,也不是一个指令,仅仅是一个特殊的tag而已。 使用 ng-container 渲染所包含的模板内容,不包含自身。

       

My name is wyl.

    

What is you name?

  
  

My name is wyl.

  

What is you name?

另外,ng 中常见错误之一的 forif 不能写在同一标签上(在一个宿主元素上只能应用一个结构型指令),利用 ng-container 标签可以在实现功能的基础上减少层级的嵌套。

2.2 ng-template

先来看下面一段代码


    

 In template, no attributes. 

    

 In ng-container, no attributes. 

浏览器输出结果是:

In ng-container, no attributes.

中的内容不会显示。当在上面的模板中添加 ngIf 指令:


   

 ngIf with a ng-template.

   

 ngIf with an ng-container.

浏览器输出结果是:

ngIf with a ng-template.
ngIf with an ng-container.

2.3 ng-template 的配合使用


     暂时搜索不到您要的数据喔


     快快开始获取吧!

2.4 ngTemplateOutlet

插入 ng-template 创建的内嵌视图。 ngTemplateOutlet 是一个结构型指令,接收一个 TemplateRef 类型的值;



  I am span in template {{title}}

*ngTemplateOutlet = "templateRefExp; content: contentExp "

使用如下:

@Component({
  selector: 'ng-template-outlet-example',
  template: `
    
    
         
         
    Hello     Hello {{name}}!     Ahoj {{person}}! ` }) class NgTemplateOutletExample {   myContext = {$implicit: 'World', localSk: 'Svet'}; }

2.5 利用 ngTemplateOutlet 进行内容投影

@Component({
    selector: 'app-card',
    template: `
		
		  
		  	
		  
		
`
})
export class AppCardComponent {

	@ContentChild('header', { static: true }) headerTemplate: TemplateRef;

	public title = 'Test';
	public otherDate = {
	 	auth: 'me',
	 	name: 'appCard'
	};
}

使用


  
    

Angular

 {{label}} (Test) and  {{otherDate | json}} ({auth: 'me', name: 'appCard'})   

到此,关于“angular中怎么进行内容投影”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注创新互联网站,小编会继续努力为大家带来更多实用的文章!


网站名称:angular中怎么进行内容投影
分享路径:http://tjjierui.cn/article/gphjcd.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP