更改另一个组件的值,但不反映在DOM上

时间:2019-11-27 10:00:18

标签: angular

最初,我是通过一个函数在home组件中设置值,而我是在profile组件中触发函数,但是DOM上的值未更改且profile是子组件

这是代码

主页组件:

//Value is not getting changed after trigger the function in profile component

@Component({
  template: `
     <span>data Filter: {{dataname}}</span>    
    `,
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
dataname = '';
ngOnInit() {
    this.productlist('abcd');
}

 productlist(any){
     this.dataname = any;
 }
}

个人资料组件:

import { HomeComponent } from '../home/home.component';
@Component({
  providers: [HomeComponent],
  template: `
     <input type="text" [(ngModel)]="dataname"/>
      <button type="button" class="btn btn-primary" (click)="saveUser()">Save</button>
    `,
  styleUrls: ['./Profile.component.css'],
})
export class ProfileComponent {
  dataname = '';
  constructor(
    private home : HomeComponent, 
  ) {
  }
 ngOnInit() {
 }
saveUser(){
   this.home.productlist(this.dataname);
}
}

当我在配置文件组件中触发但在DOM中未更改时,我正在函数中获取值 请帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

尝试这样:

Working Demo

创建DataChange服务:

export class DataChangeService {
  constructor() {}

  public status: BehaviorSubject<string> = new BehaviorSubject<string>("");

  changeData(value: any) {
    this.status.next(value);
  }
}

profie.component:

  constructor(private changeService:DataChangeService) {}

  saveUser() {
    this.changeService.changeData(this.dataname);
  }

home.component

  constructor(private changeService: DataChangeService) {}

  ngOnInit() {
    this.changeService.status.subscribe(val => {
      this.dataname = val;
    });
  }