【问题标题】:Use variable of one component in another component in the same file在同一文件中的另一个组件中使用一个组件的变量
【发布时间】:2019-05-13 06:05:14
【问题描述】:

我在同一个文件中定义了两个组件,我试图将一个组件的一个变量访问到另一个变量中,得到this 回答,但是当我尝试引用它时,get SomeValue() 函数没有出现在其他类中。

在提供的链接上给出答案:

export class Demo {
const sum = 10;

get SumValue() {
    return this.sum;
}
}

导入-->演示

export class Demo2 {
   private sum: number;
   this.sum = Demo.SumValue();
}

我可以使用共享服务,但不想只为一个变量使用它。

这个答案有什么我遗漏的吗?

【问题讨论】:

  • 这两个组件之间是什么关系,例如它的兄弟姐妹或父子关系?
  • @R.Viral 兄弟姐妹
  • 可能是您在模板中缺少@Input()

标签: angular dragula ng2-dragula angular-dragula


【解决方案1】:

这叫Component Interaction

您需要为此使用@Input

如果您要发送子的属性正在异步更改,那么您需要使用EventEmitter

查看this link 以供参考

这是一个简单的例子:

子组件

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

@Component({
    selector: 'child-component',
    template: `<h2>Child Component</h2>
               current count is {{ count }}
    `
})
export class ChildComponent {
    @Input() count: number;
}

父组件:

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

@Component({
  selector: 'app-root',
  template: `
        <h1>Welcome to {{title}}!</h1>
        <button (click)="increment()">Increment</button>
        <button (click)="decrement()">decrement</button>
        <child-component [count]=Counter></child-component>` ,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Component Interaction';
  Counter = 5;

  increment() {
    this.Counter++;
  }
  decrement() {
    this.Counter--;
  }
}

Reference

【讨论】:

    猜你喜欢
    • 2016-06-14
    • 2014-02-22
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    相关资源
    最近更新 更多