如何从.ts文件访问angular2中的html文件的方法?

时间:2017-04-17 12:32:46

标签: angular angular2-modal

我是Angular2的初学者,我创建了一个模态对话框,这里是我的HTML文件。      index.html文件: -



 <button type="button" class="btn btn-default"                    (click)="modal.open()">Open</button>
    
        <modal #modal>
        <modal-header [show-close]="true">
            <h4 class="modal-title">I'm a modal!</h4>
        </modal-header>
        <modal-body>
&#13;
&#13;
&#13;

        Here i want to call show() method from .ts file.
    </modal-body>
    <modal-footer [show-default-buttons]="true"></modal-footer>
    </modal>

点击“打开”按钮后,我想调用.ts文件中的show(){....}    我希望在<modal-boady></modal-body>标记内显示。

这是我的hello.component.ts文件: -

&#13;
&#13;
import {Component, View} from "angular2/core";
@Component({
  selector: 'my-app',
  templateUrl: './index.html'
  })
  
  export class  HeapMemoryGraphComponent implements OnInit {
   constructor(){}
   ngOnInit() {
    this.show();
   }
   show(){
    console.log("=====show()=======");
   }
  }
&#13;
&#13;
&#13;

我怎么能这样做?请指导我。

感谢。

2 个答案:

答案 0 :(得分:1)

有几种方法可以在组件中获取元素。 但是大多数可以理解的指南就在这里。

http://valor-software.com/ngx-bootstrap/#/modals

请检查儿童模式

<button type="button" class="btn btn-primary" (click)="showChildModal()">Open child modal</button>
<div bsModal #childModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title pull-left">Child modal</h4>
        <button type="button" class="close pull-right" aria-label="Close" (click)="hideChildModal()">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        I am a child modal, opened from parent component!
      </div>
    </div>
  </div>
</div>

import { Component, ViewChild } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap/modal';

@Component({
  selector: 'demo-modal-child',
  templateUrl: './child.html'
})
export class DemoModalChildComponent {
  @ViewChild('childModal') public childModal:ModalDirective;

  public showChildModal():void {
    this.childModal.show();
  }

  public hideChildModal():void {
    this.childModal.hide();
  }
}

正如您在此处所见,组件被引用为.ts文件中的模态元素的句柄。

答案 1 :(得分:0)

html文件:

<input class="search-text" type="text" (keyup)="onKeyUp($event)">
<button type="button" [disabled]="!isValidForSearch()"  class="btn btn-primary" (click)="getUsers()">Search</button>

ts档案:

//Here I am getting the value entered in the text box
onKeyUp(event){
   this.searchText = event.target.value;
}

//Here I am enabling the button if user enters any text in the search text box other wise it will be disabled 
isValidForSearch() {
   var isValid = false;
   if(this.searchText != '' && this.searchText != undefined) {
       isValid = true;
   }
   return isValid;  
}

我希望这对你有所帮助。