【问题标题】:Facing issue while calling @viewchild in angular以角度调用@viewchild 时面临问题
【发布时间】:2020-01-08 01:55:03
【问题描述】:

大家好,我正在使用 Angular 并想在 ts 文件中调用 @viewChild,但遇到错误“装饰器在此处无效。”找不到针对我的问题的任何具体解决方案

我已经尝试了很多关于这个问题的链接,包括角度文档、stackoverflow、youtube,但无法找到任何适合我的问题的解决方案

import { Component, OnInit, ViewChild } from '@angular/core';
import * as $ from 'jquery';

@Component({
    selector: 'app-upload-card-details',
    templateUrl: './upload-card-details.component.html',
    styleUrls: ['./upload-card-details.component.css']
})
export class UploadCardDetailsComponent implements OnInit {
    @ViewChild(draganddropimage)
    constructor() {}

ngOnInit() {}
    }

HTML:Code
<div class="modal fade custom-modal-setting" id="drag-and-drop-image" #draganddropimage tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"></div>

【问题讨论】:

    标签: angular angular-components


    【解决方案1】:

    只是在解决同样的问题。 你需要在装饰器和构造器之间放置一些东西:

    export class SomeComponent implements OnInit {
      @ViewChild(SomeChildComponent, { static: true })
    
      someVariable: SomeChildComponent; // this row is the magic (otherwise you decorate the constructor)
    
      constructor() {}
    

    【讨论】:

      【解决方案2】:

      您需要声明一个变量并为其添加装饰器:

      import { Component, OnInit, ViewChild } from '@angular/core';
      import * as $ from 'jquery';
      
      @Component({
          selector: 'app-upload-card-details',
          templateUrl: './upload-card-details.component.html',
          styleUrls: ['./upload-card-details.component.css']
      })
      export class UploadCardDetailsComponent implements OnInit {
          @ViewChild('draganddropimage')
          private draganddropimage: ElementRef; 
      
          constructor() {}
      
          ngOnInit() {}
          }
      }
      

      【讨论】:

      • 嗨 @Mustapha 非常感谢您的回复,但我得到的仍然是它不起作用的错误是 error TS2554: Expected 2 arguments, but got 1.
      • 我编辑了答案。您必须将 viewChild 的名称作为字符串 @ViewChild('draganddropimage')
      • 如果您使用的是 Angular 8,您需要添加 { static: true } 查看此帖子stackoverflow.com/questions/56473899/…
      【解决方案3】:

      从 Angular 8 开始,您需要在 ViewChild 中添加 { static: true }

      试试这样:

      @ViewChild('draganddropimage', { static: true }) dragDropImageRef: ElementRef;
      

      【讨论】:

        【解决方案4】:

        您需要导入 ElementRef,然后使用这个 sn-p 来使用 ViewChild 获取您的模板引用:

        @ViewChild('draganddropimage') dragDropImageRef: ElementRef;
        

        【讨论】:

        • 嗨 ilyas 感谢您的回复,但仍然无法解决 错误 TS2554: Expected 2 arguments, but got 1.
        【解决方案5】:

        我认为你装饰了构造函数,尝试为@ViewChild(draganddropimage) draganddropimage 设置一个名称

        【讨论】:

          猜你喜欢
          • 2018-07-30
          • 1970-01-01
          • 2020-05-16
          • 1970-01-01
          • 2018-01-28
          • 1970-01-01
          • 2016-02-17
          • 1970-01-01
          • 2022-08-13
          相关资源
          最近更新 更多