与其他组件共享财产

时间:2019-10-25 14:35:38

标签: angular

我只是在学习Angular,我想与其他组件共享currentSection的价值。因此,这意味着我的组件sections包含属性currentSection,而我的组件form应该接收它的值。

组件“部分”

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-sections',
  templateUrl: './sections.component.html',
  styleUrls: ['./sections.component.sass']
})
export class SectionsComponent implements OnInit {
  public currentSection: string;

  constructor() { }

  toggleSection(section) {
    this.currentSection = section;
  }

  ngOnInit() {
  }

}

这是我尝试的方式:

  @Output() public section = new EventEmitter();

  public currentSection: string;

  constructor() { }

  toggleSection(section) {
    this.currentSection = section;
    this.section.emit(section);
  }

组件“表”中的HTML

<form [ngClass]="section">

但是我收到错误消息未解决的变量或类型部分

我该如何解决?

Stackblitz

3 个答案:

答案 0 :(得分:1)

如果您需要@Input部分以形成组件。您需要在表单组件中将节作为@Input()

 @Input() section: string;

与父app-sections模板共享如下内容:

出现错误是因为section被定义为输出事件,而没有在form-component中定义为输入。

选中此example for more details on @input

答案 1 :(得分:1)

您快完成了:

在您的app-form中添加如下输入:

@Input() section: string;

然后在app-sections中共享从app-formAppComponent的部分(就像中介一样)

<app-sections (section)="onSectionChanged($event)"/app-sections>
<app-form [section]="section"></app-form>
export class AppComponent  {
  section: string

  onSectionChanged(section) {
    this.section = section;
  }
}

答案 2 :(得分:0)

进行以下更改,您应该会很好。.检查控制台日志

更新您的栏目组件(子组件)ts

@Output() public currentSection = new EventEmitter<string>();


toggleSection(section) {    
this.currentSection.emit(section);
console.log(section);
}

更新表单组件ts

import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-form',
template: `<app-sections (currentSection)='displaySection($event)'></app-sections>`
})

export class FormComponent implements OnInit {

 constructor() { }

ngOnInit() {

}

displaySection(section) {
    console.log("Section ",section);
}
}

更新表单组件html

<form></form>

更新您的应用程序组件html

<app-form></app-form>