Angular2 - 在组件外部调用Component的方法

问题描述 投票:3回答:2

我试图在点击事件上更新按钮的标签。我有以下代码。方法setText()没有被点击事件调用。

此外,如果尝试在模板中包含调用本身

<button (click)="setText('new name')"></button>

有用。

但是我希望公开这个api并想调用这个方法

<mybutton (click)="setText('new name')"></button>

谁能告诉我这里的错误是什么?我正在使用angular2 beta。

app.ts

import {Component, View, Input, Output, EventEmitter} from 'angular2/core';

@Component({
    selector: 'mybutton',

})
@View({
    template: `<button>{{label}}</button>`

})

export class MyButton {      

    @Input() label: string;
    @Output() click = new EventEmitter();   

    setText(newName: string) {
        this.label = newName;            
    }
}

的index.html

<html>
    <head>
        <title>Angular 2 QuickStart</title>
        <!-- 1. Load libraries -->
        <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
        <script src="node_modules/systemjs/dist/system.src.js"></script>
        <script src="node_modules/rxjs/bundles/Rx.js"></script>
        <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
        <!-- 2. Configure SystemJS -->
        <script>
            System.config({
                packages : {
                    app : {
                        format : 'register',
                        defaultExtension : 'js'
                    }
                }
            });

            System.import('app/boot').then(null, console.error.bind(console));
        </script>
    </head>
    <!-- 3. Display the application -->
    <body>
        <mybutton [label]="'My  Button'" (click)="setText('New Name')" ></mybutton>
    </body>
</html>
angular angular2-directives
2个回答
3
投票

实际上,在定义@Ouput时,这意味着您希望组件发出事件

click.emit(null);

您的代码有点奇怪的是,您尝试在外部管理组件的内部事件。所以我认为你的组件中不需要这个Output ......

使用以下代码,您希望在父组件中处理组件的click事件。所以setText方法将是这个父组件中的一个(不是子组件中的一个)。

<mybutton (click)="setText('new name')"></button>

如果要与mybutton组件交互以在click事件上更新其按钮标签,则可以获取对此组件的引用并更新label属性。

@Component({
  (...)
  template: `
    <mybutton #comp (click)="comp.label = 'new name'"></button>
  `,
  directives: [ MyButton ]
})
(...)

以下是mybutton组件的代码:

@Component({
  selector: 'mybutton',
  template: `<button>{{label}}</button>`
})
export class MyButton {      
  @Input() label: string;

  constructor() {
    this.label = 'test';
  } 

  setText(newName: string) {
    this.label = newName;            
  }
}

蒂埃里


1
投票

只是用

template: `<button (click)="setText()">{{label}}</button>`

在你的index.html只是<mybutton></mybutton>

© www.soinside.com 2019 - 2024. All rights reserved.