在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中。