【问题标题】:Angular popup not working from TS file, but works from HTML角度弹出窗口不适用于 TS 文件,但适用于 HTML
【发布时间】:2018-11-27 06:52:32
【问题描述】:

我有一个只有一个按钮的 Angular 应用程序。

点击按钮后,我将能够打开一个弹出窗口

index-component.html(登陆页面)

<button type="button" class="btn btn-primary" (click)=warning.show()>
</button>
<app-modal #warning>
</app-modal>

index-component.ts

 @Component({
      selector: 'app-modal',
      templateUrl: './model-component.html',
      styleUrls: ['./model-component.css']
    })

  export class IndexComponent implements OnInit {
    public show(): void {
   this.visible = true;

   setTimeout(() => this.visibleAnimate = true, 100);  
 }
}

model-component.html(弹出组件)

<div class="modal-dialog modal-sm" role="document">    
    <div class="modal-content">
     Some data for popup here..........
    </div>
</div>

上面的打开弹窗的执行是通过线路发生的

(click)=warning.show()

这是完美的工作。

现在我需要将此调用移至 TS 文件。

所以,在 index-component.ts 中我需要调用 warning.show()

但是,我无法在 TS 文件中获取 #warning 的实例。

我将如何实现这一目标?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您可以像这样使用@viewChild 获取在 Angular 中定义的局部变量的实例 -

    <button type="button" class="btn btn-primary" (click)=getInstance()>
    </button>
    
    
    export class IndexComponent implements OnInit, AfterViewInit {
    @ViewChild('warning') warning: any;
      ngAfterViewInit() {
          console.log(this.warning);
      }
      getInstance() {
        console.log(this.warning);
      }
    }
    

    Working Example for the same

    【讨论】:

    • @ViewChild('warning') 警告:任何;它说未使用的标签
    • @SmartestVEGA 请用示例检查我的更新答案
    • view child 应该在export里面
    • Opps,只是发错了,反正代码写得对,你可以看看例子
    • 如果我需要从 something.service.ts 调用它,我没有任何 html 页面来放置
    【解决方案2】:

    有两种方法可以实现这一点

    @Component({
          selector: 'app-modal',
          templateUrl: './model-component.html',
          styleUrls: ['./model-component.css']
        })
    
      export class IndexComponent implements OnInit {
      @ViewChild('warning') warning: any;
    
     onButtonClick() {
        this.warning.show()
     }
    }
    

    这里的Html按钮点击应该是(click)="onButtonClick()"

    或者您可以将引用作为 .html 文件中的参数传递

    @Component({
          selector: 'app-modal',
          templateUrl: './model-component.html',
          styleUrls: ['./model-component.css']
        })
    
      export class IndexComponent implements OnInit {
    
    
     onButtonClick(warning:any) {
        warning.show()
     }
    }
    

    这里的Html按钮点击应该是(click)="onButtonClick(warning)"

    【讨论】:

    • 很好,但是当我们有可用选项时,将引用作为参数传递并不是一个好方法。
    • @PardeepJain,谢谢,但是如果没有使用警告组件 else where ,则无需声明变量和分配(代码最小化。内存浪费)。对不起,如果我错了
    • 如果我需要从 something.service.ts 调用它,我没有任何 html 页面来放置
    • @ViewChild('warning') 警告:任何; ngAfterViewInit() { this.something.service.warningPopup = this.warning; }
    猜你喜欢
    • 2016-06-05
    • 1970-01-01
    • 2012-11-06
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多