如何在两个组件中使用一个变量?

时间:2018-08-31 21:53:20

标签: angular

这是一个用Angular 6构建的项目。我有两个类,一个和两个。我想在两个类中都使用一个变量。我已经导入了该类,但是不确定如何访问该变量。

如何在two.component中使用one.component中的“ num:number = 2018”?

one.component.ts:

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

@Component({
  selector: 'app-one',
  templateUrl: './one.component.html',
  styleUrls: ['./one.component.css']
})
export class OneComponent implements OnInit {

  num:number = 2018;

  constructor() { }

  ngOnInit() { }

  getNum() : number{
    return this.num;
  }

}

two.component.ts:

import { Component, OnInit } from '@angular/core';
import { OneComponent } from '../one/one.component';

@Component({
  selector: 'app-two',
  templateUrl: './two.component.html',
  styleUrls: ['./two.component.css']
})
export class TwoComponent implements OnInit {

  constructor() { }

  ngOnInit() {  }

}

1 个答案:

答案 0 :(得分:0)

在Angular中,您只有一个根组件。这意味着所有其他组件都是同一组件的子组件,并且从您的项目中选择2个随机组件,它们始终具有相同的父代。

您可以在公共父级中定义变量,然后将其作为输入输入onetwo

让我们假设one.componenttwo.component都是app.component的子代。然后,您在app.component模板中:

<app-one [num]="number"></app-one>
<app-two [num]="number"></app-two>

,您需要在app.component类中定义变量(在其他地方?从逻辑上讲,没有理由将变量放在one中而不是two中)

如果onetwo更改变量怎么办?好吧,这取决于..

如果number是字符串,数字或布尔值,则会将其复制,并且app-oneapp-two将使用其自己的本地副本。

因此,您有三种解决方案:

  • 将变量包装在对象中。您将传递任何对象的引用作为输入。如果对象的值更改,更改检测机制将更新所有树

  • 使用@Output()更新变量。变量可能会随着对事件的反应而改变。当此事件发生时,还触发EventEmitter。

  • 使用redux

相关问题