'Element | 类型的参数null' 不可分配给类型为 'Element' 的参数。类型 'null' 不能分配给类型 'Element'。角

时间:2021-06-13 15:43:30

标签: angular typescript

我正在尝试使用 bs-stepper 创建一个角度步进器表单,我已经安装了 npm 并在 index.html 中添加了 CDN, 当我在我的 componenet.ts 中实现代码时,它会显示此错误:

any

我的 component.ts:

Argument of type 'Element | null' is not assignable to parameter of type 'Element'.
  Type 'null' is not assignable to type 'Element'.

51     this.stepper = new Stepper(document.querySelector('#stepper1'), {
                                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

2 个答案:

答案 0 :(得分:0)

如错误所示,您正在尝试传入可能为 null 的对象。 document.querySelector 和其他与 DOM 相关的查询方法的类型是 Element|null。这里,Stepper 类只接受 Element 类型的参数。

只需进行空类型检查并在 ngOnInit 中分配值。

const stepperElement = document.querySelector('#stepper1');

    if(stepperElement !== null){
    this.stepper = new Stepper(stepperElement , {
          linear: false,
          animation: true
        })
    }

答案 1 :(得分:0)

需要先从 ngAfterViewInit 中的 querySelector 中获取 value 元素,如果不在 ngOninit 上为一个常量,然后给它添加一个 null 检查。

喜欢:

const el = document.querySelector('#stepper1');
if(!!el) {
  this.stepper = new Stepper{el, {    
    linear: false,
    aniimation:true
  }
 }
}