从Angular 2中的子组件更新父组件属性

新手上路,请多包涵

我正在使用 @input 从父组件接收属性,以便在子组件的元素之一中激活 CSS 类。

我能够从父级接收属性并激活类。但这仅适用于一次。我从父组件接收的属性是一个布尔数据类型,当我从子组件将它的状态设置为 false 时,它在父组件中不会改变。

Plunkr: https ://plnkr.co/edit/58xuZ1uzvToPhPtOING2?p=preview

应用程序.ts

 import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { HeaderComponent } from './header';
import { SearchComponent } from './header/search';

@Component({
  selector: 'my-app',
  template: `
    <app-header></app-header>
  `,
})
export class App {
  name:string;
  constructor() {
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, HeaderComponent, SearchComponent ],
  bootstrap: [ App ]
})
export class AppModule {}

头文件.ts

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

@Component({
  selector: 'app-header',
  template: `<header>
              <app-search [getSearchStatus]="isSearchActive"></app-search>
              <button (click)="handleSearch()">Open Search</button>
            </header>`
})
export class HeaderComponent implements OnInit {
  isSearchActive = false;

  handleSearch() {
    this.isSearchActive = true
    console.log(this.isSearchActive)
  }

  constructor() { }
  ngOnInit() { }
}

标头/search.ts

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

@Component({
  selector: 'app-search',
  template: `<div id="search" [class.toggled]="getSearchStatus">
              search
              <button  (click)="getSearchStatus = false" class="close">Close Search</button>
            </div>`
})
export class SearchComponent implements OnInit {
  @Input() getSearchStatus: boolean;

  constructor() { }

  ngOnInit() {

  }
}

请检查上面给出的 plunker。开放式搜索功能只工作一次。关闭搜索后,不再触发。

@input 是否适合这种情况?请帮我解决这个问题。 (请更新插件)。

原文由 Body 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

您需要使用 2 路数据绑定。

@Input() 是一种数据绑定方式。要启用 2 路数据绑定,您需要添加一个 @Output() 对应于该属性,并带有“更改”后缀

@Input() getSearchStatus: boolean;
@Output() getSearchStatusChange = new EventEmitter<boolean>();

当您要将对您的财产所做的更改发布给父母时,您需要通知父母:

 this.getSearchStatusChange.emit(newValue)

在父级中,您需要对该属性使用香蕉盒中的表示法:

 [(getSearchStatus)]="myBoundProperty"

您还可以绑定到属性并在子属性更改时触发回调:

 [getSearchStatus]="myBoundProperty" (getSearchStatusChange)="myCrazyCallback($event)"

plnkr

原文由 n00dl3 发布,翻译遵循 CC BY-SA 3.0 许可协议

另一种方法:使用 rxjs/BehaviorSubject 在不同组件之间传递状态。

这是 plunkr

我用后缀“Rxx”命名主题,因此 searchStatus 的 BehaviorSubject 将是 searchStatusRxx。

  1. 在父组件中初始化它,如 searchStatusRxx = new BehaviorSubject(false);
  2. 使用 @Input 将其传递给子组件
  3. 在子模板中,您执行异步管道。
  4. 在父母和孩子中,您都执行 searchStatusRxx.next(value) 来更改最新值。

原文由 Timathon 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进