使用@Input 和@Output 传递事件和 url

Passing Events and urls with @Input and @Output

angular2 的初学者而不是经验丰富的网络开发人员,所以对于这个问题中存在的任何极端愚蠢,我深表歉意...

我在为下拉列表 select 制作组件时遇到了一些问题。我的目标是在另一个组件中使用此组件,并在每次按下 select 列表中的选项时在父组件中调用一个方法。

这是下拉输入(子组件)的模板:

    <div>
    <select>
        <option (click)="clicked($event)" *ngFor="let option of options">{{option.label}}</option>
    </select>
    </div>

下面是 class 的样子:

export class DropdownInput {
// List of options for the dropdown to have
public options: InputOption[];

// Url for controller method to get options
@Input() url = "/api/LogViewer/GetOpts";

@Output() clickEvent = new EventEmitter();

public clicked(event) {
    this.clickEvent.emit(event);
}

// Get list of options on construction
constructor(http: Http) {
    http.get(this.url).subscribe(result => {
        this.options = result.json();
    });
}

interface InputOption {
    value: string;
    label: string;
}

因此,据我了解,每个下拉选项在单击时都绑定了 'clicked()' 方法。该方法应该将点击事件传递给父级绑定到 'clickEvent'.

的方法

以下是我在父级中使用此组件的方式:

<dropdown-input (clickEvent)="typeClick($event)"></dropdown-input>

并且父组件在class里面有这个方法:

public typeClick(event) {
    console.log(event);
}

这个设计是否存在根本性缺陷,或者我只是犯了一个愚蠢的错误? 运行 时我没有收到任何错误或任何信息,但更改下拉选项也不会记录任何内容。

第二个问题:有没有什么好的方法可以将 url 作为输入传递给下拉组件?只需将“[url]="/api/LogViewer/GetOpts" 放在 dropdown-input 的用法中就会出错。

谢谢!

P.S。为了避免 XY 问题,我正在做所有这些,因为我想创建一个组件,它基本上是一个我可以动态创建的输入面板(文本框、下拉列表 selects、单选按钮、日历)在许多不同的页面上(用于在数据 table 之上进行过滤等)。我想这类似于一个表单,是否已经有解决方案?

您正在监听选项中的 (click) 事件,但您应该监听 change 事件。当您想要传递选定的值时,您还将实际事件传递给父组件。你可以这样做:

<select (change)="onChange($event.target.value)">

如果您这样做,将使用所选的值调用 onChange 方法,而不是实际的更改事件。