【问题标题】:Shared html in angular4 not working as expected?angular4 中的共享 html 无法按预期工作?
【发布时间】:2017-11-30 02:19:20
【问题描述】:

我在每个页面中都使用共享的 html 进行搜索

search.component.html

   <form class="p-2" (ngSubmit)="searchHere(query)" #customersearch="ngForm">
  <div class="input-group custom-search-form float-right">
<input type="search" class="form-control" name="search" placeholder="Search..." [(ngModel)]="searchQuery" />
<span class="input-group-btn">
            <button class="btn btn-default-sm" type="submit">
                <i class="fa fa-search"></i>
            </button>
        </span>
  </div>
 </form>

搜索组件.ts

  @Component({
moduleId: module.id,
selector: 'search-items',
templateUrl: './search.component.html',
           })

    export class SearchComponent {

@Output() search = new EventEmitter<string>();
searchQuery:string;

searchHere(text?: string) {
    console.log(text)
    this.search.emit(text);
}

   }

我在客户组件 html 中使用它

 <search-items (search)="filter($event,'q')"></search-items>

当我点击搜索按钮时,它工作正常,但由于共享的 html 是一个表单,当我点击输入时,搜索也应该工作。

但是当我点击进入它的调用过滤函数两次。 首先它传递确切的参数,第二次它传递一个事件类型作为参数。如何预防?

出了什么问题?

【问题讨论】:

    标签: angular angular2-forms angular2-directives


    【解决方案1】:

    我的行为和你一样。我不知道为什么这个问题与名称“搜索”输出事件发射器变量有关。请将其更改为任何其他名称,例如“测试”并在您的

    中执行此操作
    @Output() test= new EventEmitter<string>();
    
    searchData() {
        this.test.emit(this.searchQuery);
    }
    

    <search-items (test)="filter($event)"></search-items>
    

    这会起作用

    【讨论】:

    • 仍然调用过滤器方法两次。这不是我问题的答案。
    • 当我点击输入后点击回车按钮时,它调用该方法两次,第一次 $event 有文本。但第二次它有一个事件类型的对象。
    • 我知道,它会起作用,但由于我共享的 html 是一个表单,点击进入该方法会调用两次......仍然在发生。
    • 这不是发生在我身上。它只是在我使用搜索变量时发生。如果你可以分享那个 plunker。我可以在这个问题上为你提供帮助
    • 我使用的 angularr 版本是 angular 4
    猜你喜欢
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    • 2019-09-24
    • 1970-01-01
    相关资源
    最近更新 更多