【问题标题】:call method from a component to main component angular2从组件调用方法到主要组件angular2
【发布时间】:2017-06-09 19:05:10
【问题描述】:

我的问题是我有一个组件具有我希望我的 app.component.html 可以访问的功能

book.component.html

<div class="form-inline">
        <input id="inputSearchBar" class="form-control mr-sm-2" type="text" placeholder="Search" [(ngModel)]="Text">
        <button class="btn btn-outline-info my-2 my-sm-0" type="submit" (click)="onSearch()">Search</button>
    </div>

现在这正在工作,因为我的 book.component.html 上有这行代码,我想要在导航栏内的 app.component.html 上使用它

app.component.html

<header>
  <nav class="navbar navbar-toggleable-md navbar-inverse bg-inverse">
    <button class="navbar-toggler navbar-toggler-right" type="button" 
    data-toggle="collapse" 
    aria-controls="navbarColor01"
    aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
    <a class="navbar-brand" href="#">Navbar</a>
    <div class="collapse navbar-collapse" id="navbarColor01" >
      <ul class="navbar-nav mr-auto">
        <li class="nav-item active">
          <a class="nav-link" href="#" [routerLink]="['']">Home <span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#" [routerLink]="['about']">About</a>
        </li>
          <li class="nav-item">
          <a class="nav-link" href="#" [routerLink]="['books']">Books</a>
        </li>
         <li class="nav-item">
          <a class="nav-link" href="#" >Register</a>
        </li>
          <li class="nav-item">
          <a class="nav-link" href="#" [routerLink]="['login']">Login</a>
        </li>
      </ul>

    </div>
  </nav>
</header>

我想将该搜索框作为我的导航栏的一部分并且它可以正常工作,我应该在我的组件上添加什么或者我应该做些什么来使它工作。

【问题讨论】:

    标签: html function angular navbar


    【解决方案1】:

    您可以在此处使用父子关系。为搜索栏创建组件并添加父组件。

    1) 像这样创建搜索组件

    @Component({
      selector: 'search-component',
    })
    export class searchcomponent  { }
    

    2) 在父 HTML 中添加

    app.component.html

    <header>
    <search-component>  </search-component>
    </header>
    

    更多信息请查看此链接https://angular.io/docs/ts/latest/cookbook/component-communication.html

    【讨论】:

    • ty 回复,但问题是我的 book.component.html 中的内容比那个特定的搜索框要多得多,如果我要使用它,那么它们都会出现在导航栏上,我只想显示那行特定的代码
    【解决方案2】:

    【讨论】:

    • 我必须稍后检查一下,因为它有很多信息,谢谢分享,但我只是认为有一种更简单的方法可以做到这一点,我一定会检查一下稍后。
    猜你喜欢
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 2020-10-29
    • 2017-04-22
    • 2019-05-13
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    相关资源
    最近更新 更多