Angular 2更改了类中的数据

时间:2021-09-24 19:45:47

Why I can't change data in View from function in class?

为什么我不能在View中从类中的函数更改数据?

wrap.component.ts

@Component({
    selector: 'wrap',
    templateUrl: './templates/wrap.html'
})

export class WrapComponent {
    public test: string;
    constructor () {
        this.test = 'Hello world';
    }

    fun () {
        this.test = 'SPAM';
    }
}

express.component.ts

import {WrapComponent} from './wrap.component';
export class Express {
    constructor () {
        new WrapComponent().fun();
    }
}

wrap.html

<h2>{{test}}</h2>

Why in view test variable is 'Hello world'?

为什么在视图中测试变量是'Hello world'?

1 个解决方案

#1


0  

In fact, you instantiate by your own the WrapComponent component from the Express class. Angular2 manages by itself component instances. This means that you don't share the same instance.

实际上,您可以自己实例化Express类中的WrapComponent组件。 Angular2自己管理组件实例。这意味着您不共享同一个实例。

To help you further, I need to know which kind of entity the Express class represents... Another component, a service, ...

为了进一步帮助您,我需要知道Express类代表哪种实体......另一个组件,服务,......

You could call the fun method from a click event within the WrapComponent component:

您可以从WrapComponent组件中的click事件调用fun方法:

<div (click)="fun()">Have fun!</div>

Hope it helps you, Thierry

希望它对你有帮助,蒂埃里

#1


0  

In fact, you instantiate by your own the WrapComponent component from the Express class. Angular2 manages by itself component instances. This means that you don't share the same instance.

实际上,您可以自己实例化Express类中的WrapComponent组件。 Angular2自己管理组件实例。这意味着您不共享同一个实例。

To help you further, I need to know which kind of entity the Express class represents... Another component, a service, ...

为了进一步帮助您,我需要知道Express类代表哪种实体......另一个组件,服务,......

You could call the fun method from a click event within the WrapComponent component:

您可以从WrapComponent组件中的click事件调用fun方法:

<div (click)="fun()">Have fun!</div>

Hope it helps you, Thierry

希望它对你有帮助,蒂埃里