Angular 6: 让指令从ng-content对父组件可见,使用Angular Material
创始人
2024-10-16 05:30:21
0

在Angular 6中,可以使用Angular Material的cdkPortal指令和PortalOutlet类来实现将子组件的内容传递给父组件。下面是一个示例代码:

首先,安装Angular Material和CDK库:

npm install --save @angular/material @angular/cdk

在app.module.ts中导入和添加Angular Material和CDK模块:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { PortalModule } from '@angular/cdk/portal';
import { MatButtonModule } from '@angular/material/button';

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

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    PortalModule,
    MatButtonModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

接下来,在父组件的模板中使用ng-template和cdkPortal指令:





在父组件的代码中,定义一个变量来保存子组件的内容,并在需要时将其传递给父组件:

// parent.component.ts
import { Component, ViewChild, TemplateRef } from '@angular/core';
import { CdkPortalOutlet, Portal } from '@angular/cdk/portal';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {
  @ViewChild(CdkPortalOutlet) portalOutlet: CdkPortalOutlet;

  childContent: Portal;

  showChildContent() {
    this.childContent = new TemplatePortal(this.childTemplate, this.viewContainerRef);
  }
}

最后,在子组件中定义一个ng-template,并使用cdkPortal指令将其内容传递给父组件:



  

这是子组件的内容

这样,当点击父组件中的按钮时,子组件的内容将被显示在父组件的ng-template中。

相关内容

热门资讯

5分钟辅助!wpk辅助,佛手在... 5分钟辅助!wpk辅助,佛手在线大菠萝技巧,手段教程(有挂方法)1、进入游戏-大厅左侧-新手福利-激...
八分钟辅助!wepoker私人... 八分钟辅助!wepoker私人局透视,fishpoker透视底牌,积累教程(了解有挂)1、很好的工具...
十分钟辅助!poker mas... 十分钟辅助!poker master辅助,wepoker透视app下载,妙计教程(发现有挂)1、玩家...
第八分钟辅助!poker辅助器... 第八分钟辅助!poker辅助器免费安装,德普之星有辅助软件吗,方式教程(详细教程)德普之星有辅助软件...
3分钟辅助!aapoker万能... 3分钟辅助!aapoker万能辅助器,wepoker买脚本靠谱吗,大纲教程(的确有挂)3分钟辅助!a...
第9分钟辅助!德州局透视脚本,... 第9分钟辅助!德州局透视脚本,wepoker透视是真的吗,手段教程(有挂秘诀)wepoker透视是真...
5分钟辅助!hhpoker有没... 5分钟辅助!hhpoker有没有辅助,德州局hhpoker,举措教程(有人有挂)1、进入到hhpok...
八分钟辅助!竞技联盟透视插件,... 八分钟辅助!竞技联盟透视插件,wepoker软件辅助程序,绝活教程(存在有挂)1、点击下载安装,we...
第八分钟辅助!pokernow... 第八分钟辅助!pokernow辅助工具,购买的wpk辅助在哪里下载,练习教程(揭秘有挂)1)购买的w...
三分钟辅助!werplan免费... 您好,wepoker怎么设置透视这款游戏可以开挂的,确实是有挂的,需要了解加去威信【48527505...