重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

怎么在Angular应用中创建包含组件方法-创新互联

小编给大家分享一下怎么在Angular应用中创建包含组件方法,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

创新互联公司专业为企业提供吉县网站建设、吉县做网站、吉县网站设计、吉县网站制作等企业网站建设、网页设计与制作、吉县企业网站模板建站服务,10多年吉县做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。

理解组件包含

包含组件就是指可以包含其它组件的组件, 以 Bootstrap 的卡片 (Card) 为例, 它包含页眉 (header) 、 主体 (body) 和 页脚 (footer) , 如下图所示:

怎么在Angular应用中创建包含组件方法


 
 Featured
 
   Special title treatment  With supporting text below as a natural lead-in to additional content.

 Go somewhere  
   2 days ago  

那么问题来了, 如何用 angular 来实现这样的一个组件?

这就是所谓的包含。

创建包含组件

在 angular 中, 所谓的包含就是在定义固定视图模板的同时, 通过 标签来定义一个可以放动态内容的位置。 下面就来实现一个简单的卡片组件。

卡片组件的类定义为:

// card.component.ts
import { Component, Input, Output } from '@angular/core';

@Component({
 selector: 'app-card',
 templateUrl: 'card.component.html',
})
export class CardComponent {
 @Input() header: string = 'this is header'; 
 @Input() footer: string = 'this is footer';
}

@Input 是一个声明, 允许从父组件传入任意的文本。

卡片组件的的视图模板定义为:



 
 
 
 
 
 
 
 
 
 

为了能够在其它组件中使用, 需要在对应的 AppModule 中添加声明:

import { NgModule }  from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { CardComponent } from './card.component'; // import card component

@NgModule({
 imports:  [ BrowserModule ],
 declarations: [ AppComponent, CardComponent ], // add in declaration
 bootstrap: [ AppComponent ],
})
export class AppModule { }

如果使用了 angular-cli 来生成这个组件的话, 会自动在 AppModule 中添加声明。

使用卡片组件

在另外一个组件 AppComponent 中使用刚刚创建的卡片组件的话, 代码如下所示:


Single slot transclusion

     You can put any content here  For example this line of text and

 This button    

当然, 可以使用 [header] 以及 [footer] 进行数据绑定。

选择符

接受一个 select 属性, 允许定义选择符, 可以更加精确选择被包含的内容。 打开 card.component.html , 做一些修改



 
 
 
 
 
 
 
 

注意, 添加了 select="[card-body]" , 这意味着将被包涵的元素必须有 card-body 属性, 用法也需要响应的调整一下


Single slot transclusion

     You can put any content here  For example this line of text and

 This button    

的 select 属性接受标准的 css 选择符, 比如: select="[card-type=body]" select=".card-body" select="card-body" 等等。

包含多个位置

使用 select 属性, 可以在一个组件中定义多个包含位置。 现在继续修改卡片组件, 允许页眉和页脚包含动态内容。



 
 
 
 
 
 
 
 
 
 

用法也相应的修改一下:


Single slot transclusion

   New header      You can put any content here  For example this line of text and

 This button      New footer

小结

使用包含组件, 可以将布局提取成组件, 动态指定加载的内容, 应该也是很常用的。 而至于选择符 (select), 则建议使用属性, 这样可读性比较好, 也不会破坏 html 的结构。

看完了这篇文章,相信你对“怎么在Angular应用中创建包含组件方法”有了一定的了解,如果想了解更多相关知识,欢迎关注创新互联行业资讯频道,感谢各位的阅读!


分享名称:怎么在Angular应用中创建包含组件方法-创新互联
标题URL:http://cqcxhl.cn/article/dedddj.html

其他资讯

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