Angular 2 viewchild 不工作 - 无法读取未定义的属性 nativeElement

2023-12-13

我有一个名为 multiselect.component 的组件,我访问它的 html 元素之一(<select id="category-select">)在 .ts 文件中。

多选.component.html:

<select id="category-select" multiple class="form-control">
    <option value="1">Meat</option>
    <option value="2">Dairy</option>
    <option value="3">Confectionary</option>
    <option value="4">Dessert</option>
    <option value="7">Baking</option>
    <option value="6">Grocers</option>
    <option value="5">Restaurants</option>
    <option value="8">Condiments</option>
    <option value="9">beverages</option>
</select>
<div class="form-control-icon" id="keywords-icon"></div>

多选.component.ts:

import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'multiselect',
    templateUrl: 'app/shared/multiselect.component.html',
    styleUrls: [ 'app/shared/multiselect.component.css' ]
})
export class MultiselectComponent implements OnInit {
    items = 'one two three'.split(' ');
    selectedCategories;
    allSelected;
    numberOfCategories = 9;

    ngOnInit() {
        this.selectedCategories = [];
        (<any>$("#category-select")).multiselect({
            buttonWidth: '100%',
            buttonContainer: '<div style="height: 34px;" />',
            buttonClass: 'none',
            nonSelectedText: "select categories",
            nSelectedText: ' categories',
            allSelectedText: "all categories",
            selectAllNumber: false,
            includeSelectAllOption: true,
            disableIfEmpty: true,
            onSelectAll: () => {
                this.allSelected = true;
            },
            onInitialized: () => {

            },
            onChange: (option, checked) => {
                this.changed();
            }
        });
    }

    changed() {
        this.selectedCategories = [];
        var self = this;

        $('#category-select option:selected').each(function () {
            self.selectedCategories.push(
                <any>($(this).text(), $(this).val())
            )
        });
        console.log(this.selectedCategories);
        if (this.selectedCategories.length < this.numberOfCategories) {
            this.allSelected = false;
        }
    }
}

我认为使用 jquery 访问它的方式是不好的做法。我认为可以使用@viewChild来访问它。

所以我尝试像这样更改它(我首先删除第一个 jquery 元素访问器,然后稍后再执行其余操作):

import { Component, OnInit, ViewChild } from '@angular/core';

@Component({
    selector: 'multiselect',
    templateUrl: 'app/shared/multiselect.component.html',
    styleUrls: [ 'app/shared/multiselect.component.css' ]
})
export class MultiselectComponent implements OnInit {
    items = 'one two three'.split(' ');
    selectedCategories;
    allSelected;
    numberOfCategories = 9;

    @ViewChild('category-select') select;

    ngOnInit() {
        this.selectedCategories = [];
        this.select.nativeElement.multiselect({
            buttonWidth: '100%',
            buttonContainer: '<div style="height: 34px;" />',
            buttonClass: 'none',
            nonSelectedText: "select categories",
            nSelectedText: ' categories',
            allSelectedText: "all categories",
            selectAllNumber: false,
            includeSelectAllOption: true,
            disableIfEmpty: true,
            onSelectAll: () => {
                this.allSelected = true;
            },
            onInitialized: () => {

            },
            onChange: (option, checked) => {
                this.changed();
            }
        });
    }

    changed() {
        this.selectedCategories = [];
        var self = this;

        $('#category-select option:selected').each(function () {
            self.selectedCategories.push(
                <any>($(this).text(), $(this).val())
            )
        });
        console.log(this.selectedCategories);
        if (this.selectedCategories.length < this.numberOfCategories) {
            this.allSelected = false;
        }
    }
}

我收到此控制台错误:

> EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in app/find-page/find-form.component.html:0:56
ORIGINAL EXCEPTION: TypeError: Cannot read property 'nativeElement' of undefined
ORIGINAL STACKTRACE:
TypeError: Cannot read property 'nativeElement' of undefined
    at MultiselectComponent.System.register.context_1.execute.MultiselectComponent.ngOnInit (http://localhost:3000/js/app/shared/Multiselect.component.js:29:32)
    at DebugAppView._View_FindFormComponent0.detectChangesInternal (FindFormComponent.ngfactory.js:761:90)
    at DebugAppView.AppView.detectChanges (http://localhost:3000/node_modules/@angular/core//bundles/core.umd.js:12586:18)
    at DebugAppView.detectChanges (http://localhost:3000/node_modules/@angular/core//bundles/core.umd.js:12691:48)
    at DebugAppView.AppView.detectViewChildrenChanges (http://localhost:3000/node_modules/@angular/core//bundles/core.umd.js:12612:23)
    at DebugAppView._View_FindPageComponent0.detectChangesInternal (FindPageComponent.ngfactory.js:41:8)
    at DebugAppView.AppView.detectChanges (http://localhost:3000/node_modules/@angular/core//bundles/core.umd.js:12586:18)
    at DebugAppView.detectChanges (http://localhost:3000/node_modules/@angular/core//bundles/core.umd.js:12691:48)
    at DebugAppView.AppView.detectViewChildrenChanges (http://localhost:3000/node_modules/@angular/core//bundles/core.umd.js:12612:23)
    at DebugAppView.AppView.detectChangesInternal (http://localhost:3000/node_modules/@angular/core//bundles/core.umd.js:12597:18)
ERROR CONTEXT:
[object Object]

为什么我会收到这个错误?

更改为 AfterViewInit 后,我​​现在收到此错误:

platform-browser.umd.js:937 Error: Uncaught (in promise): EXCEPTION: Error in app/find-page/find-form.component.html:13:30
ORIGINAL EXCEPTION: TypeError: Cannot read property 'length' of undefined
ORIGINAL STACKTRACE:
TypeError: Cannot read property 'length' of undefined
    at DebugAppView._View_FindFormComponent0.detectChangesInternal (FindFormComponent.ngfactory.js:890:72)
    at DebugAppView.AppView.detectChanges (http://localhost:3000/node_modules/@angular/core//bundles/core.umd.js:12586:18)
    at DebugAppView.detectChanges (http://localhost:3000/node_modules/@angular/core//bundles/core.umd.js:12691:48)
    at DebugAppView.AppView.detectViewChildrenChanges (http://localhost:3000/node_modules/@angular/core//bundles/core.umd.js:12612:23)
    at DebugAppView._View_FindPageComponent0.detectChangesInternal (FindPageComponent.ngfactory.js:41:8)
    at DebugAppView.AppView.detectChanges (http://localhost:3000/node_modules/@angular/core//bundles/core.umd.js:12586:18)
    at DebugAppView.detectChanges (http://localhost:3000/node_modules/@angular/core//bundles/core.umd.js:12691:48)
    at DebugAppView.AppView.detectViewChildrenChanges (http://localhost:3000/node_modules/@angular/core//bundles/core.umd.js:12612:23)
    at DebugAppView.AppView.detectChangesInternal (http://localhost:3000/node_modules/@angular/core//bundles/core.umd.js:12597:18)
    at DebugAppView.AppView.detectChanges (http://localhost:3000/node_modules/@angular/core//bundles/core.umd.js:12586:18)
ERROR CONTEXT:
[object Object]
    at resolvePromise (http://localhost:3000/node_modules/zone.js/dist/zone.js:538:32)
    at http://localhost:3000/node_modules/zone.js/dist/zone.js:515:14
    at ZoneDelegate.invoke (http://localhost:3000/node_modules/zone.js/dist/zone.js:323:29)
    at Object.onInvoke (http://localhost:3000/node_modules/@angular/core//bundles/core.umd.js:9245:45)
    at ZoneDelegate.invoke (http://localhost:3000/node_modules/zone.js/dist/zone.js:322:35)
    at Zone.run (http://localhost:3000/node_modules/zone.js/dist/zone.js:216:44)
    at http://localhost:3000/node_modules/zone.js/dist/zone.js:571:58
    at ZoneDelegate.invokeTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:356:38)
    at Object.onInvokeTask (http://localhost:3000/node_modules/@angular/core//bundles/core.umd.js:9236:45)
    at ZoneDelegate.invokeTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:355:43)

错误似乎出在 FindFormComponent 中。

FindFormComponent 只是具有多选功能的表单(需要填写的表单,然后将查找产品)。

以下是 FindFormComponent 中使用长度的相关 html:

<div class="row has-error-text">
    <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group btn-group" style="height:64px;">
        <div style="position: relative; display: inline-block; width: 100%;">
            <multiselect #multiselect></multiselect>
        </div>
    </div>
</div>
<div class="row error-text"  [style.display]="multiselect.selectedCategories.length < 1 && submitted ? 'block' : 'none'">
    <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 form-group input-group btn-group">
        <small>Please select at least 1 category.</small>
    </div>
</div>

你需要改变

ngOnInit() {
    this.selectedCategories = [];
    this.select.nativeElement.multiselect({

to

ngAfterViewInit() {
    this.selectedCategories = [];
    this.select.nativeElement.multiselect({

The nativeElement在视图初始化之前不可用。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 2 viewchild 不工作 - 无法读取未定义的属性 nativeElement 的相关文章

  • 如何在 Angular 库中包含图像?

    我创建了一个简单的 Angular 库 我希望我的库也显示图像 问题是 如果我将图像包含在库的模块文件夹中 然后从模块内部引用它 则会收到 404 错误 据我所知 在 Angular 项目中 图像必须放置在 assets 文件夹中 但我确实
  • 重定向到 Angular2 中 @CanActivate 内的不同组件

    有什么方法可以重定向到 Angular2 中的 CanActivate 不同的组件吗 截至今天 使用最新的 angular router 3 0 0 rc 1 这里有一些关于如何通过以下方式做到这一点的参考 CanActivate路线守卫
  • Angular 5 - 使用对象进行表单控制

    我目前正在开发一个由 Django 支持的 Angular 应用程序 该应用程序的一部分是它需要显示成员列表 成员数组看起来有点像这样 name John Smith id 3 score set name Jane Doe id 7 sc
  • Typescript Map 在使用其函数时抛出错误(mapobject.keys() 不是函数)

    我是 typescript 中的新蜜蜂 在我的 angular4 项目中 我收到一个 json 形式的地图对象 所以我声明了一个如下所示的类
  • TypeScript 编译速度极慢 > 12 秒

    只是把它放在那里看看其他人是否也遇到这个问题 我已经使用 webpack 作为我的构建工具 使用 typescript 构建了一个 Angular 2 应用程序 一切都运行良好 但是我注意到 typescript 编译超级超级慢 我现在只有
  • Angular 2 链式 Promise 并传递拒绝

    应该是一个简单的问题 但是我找不到有关如何做到这一点的文档 像这样链接一个承诺 Making a promise no problem let promise new Promise resolve reject gt let data d
  • 来自 JSON 的 Angular 8 动态表单

    我正在尝试从 JSON 模式递归生成动态表单 但我正在努力解决找不到表单控件的问题 这是代码示例 我收到这个错误 错误错误 找不到名称为 createdAt 的控件 我尝试了不同的方法 但仍然存在问题 我知道我错过了一些东西 所以请帮忙 任
  • 在d3.js中将2D形状转换为3D,并根据ANGULAR中的值调整高度

    我正在使用 d3 js v6 创建以下 2D 图表表示的 3D 图表 这个圆圈中有多个正方形 每个正方形都根据值分配了一种颜色 值越大 正方形越暗 现在我想将其转换为 3D 形状 其中当值变高时 只有特定正方形的高度会增加 因此结果在某种程
  • 如何在 angular2 中触发表单验证器?

    我创建了 angular2 Web 应用程序 我已经使用表单生成器实现了一个自定义验证器 它将在提交时工作 但我需要在其他表单控件值更改中动态触发验证 请任何人提出建议来实现这一目标 谢谢 尝试这个 this RegisterForm1 c
  • 浏览器中缺少 Angular 12 源地图

    我们已经升级到角12最近遇到一个问题 即浏览器源映射丢失 因此我们无法调试我们的组件文件 因为没有任何组件文件 谁能建议我缺少什么 Angular 12 更改了默认的 ng build 以使用 生产 配置 你想要 sourceMap 所以尝
  • 从 Angular 4 中的选择选项获取价值

    如何从 Angular 4 中的 select 选项获取值 我想将它分配给 component ts 文件中的一个新变量 我已经尝试过但没有输出任何内容 你也可以使用 ngModel 来做到这一点吗 组件 html
  • 如何更改订阅值?使用 rxJS

    我正在创建一个计时器 需要你的帮助 我刚刚学习 Angular 和 rxJS 对此我有一些疑问 我正在创建一个具有启动 停止 暂停 重置功能的计时器 并且 btn Reset 必须将我的计时器 暂停 到 300 毫秒 怎么做 D 我的启动定
  • 为 Firestore 创建的每个用户的自定义 UID

    请注意 这个问题与问题相同here https stackoverflow com questions 41155905 firebase authentication email password how to set users uid
  • Angular - Angular Material 2 步进器控件

    我使用 Angular Material 2 步进器设置了一个线性步进器 我有不同组件 组件a 组件b 组件c 中的表单 在我的主容器组件 容器组件 中 我希望有一个线性步进器 当它们的形式有效时 它可以 步进 通过每个组件 是否有某种功能
  • 我如何使用 ngRedux 测试服务

    我如何用 karma jasmine 模拟 ngRedux 的 getState 例如 我的服务通过 ngRedux 从商店获取价值 this ngRedux getState 我通过监视 getState 方法解决了这个问题 spyOn
  • 如何断点和调试角度模板?

    例如 在 React 中 您可以在视图 模板中放置一个断点并检查发生了什么 编辑 假设我想看看这里发生了什么 h2 hero name uppercase Details h2 div span id span hero id div di
  • 使用 setInterval 时 Angular2 视图未更新

    我正在使用 Angular2 RC5 我有一个奇怪的问题 在我的主要组件中 我在构造函数中用于测试目的 setInterval gt this test new Date getMilliseconds toString 500 我的模板中
  • Google Cloud Build - firebase 部署错误:“公共目录‘dist/browser’不存在,无法将托管部署到站点 PROJECT-ID”

    我正在尝试将我的 Angular Universal Web 应用程序同时部署到 Cloud Run 用于 SSR 和 Firebase Hosting 用于缓存 Cloud Run 的部署工作正常 我遵循了本指南 https cloud
  • 模块 /node_modules/angular2-cool-storage/index.d.ts 的元数据版本不匹配错误,找到版本 4,预期版本 3,

    我在运行时遇到以下错误ng build命令 删除 node modules 文件夹并 npm install 给出以下警告 npm WARN email protected cdn cgi l email protection requir
  • JS文件中的System.register是什么意思?

    在 Angular 2 中使用指令时 JS 文件中的 System register 是什么意思 我认为这个问题并不特定于 Angular2 中的指令 它是关于 ES6 TypeScript 和其他使用 SystemJS 的现代编译器的一般

随机推荐

  • 从线性探测转向二次探测(哈希冲突)

    我当前的哈希表实现是使用线性探测 现在我想转向二次探测 后来转向链接 也许还有双重哈希 我读过一些文章 教程 维基百科等 但我仍然不知道我到底应该做什么 基本上 线性探测的步长为 1 这很容易做到 当从哈希表中搜索 插入或删除元素时 我需要
  • tinyMCE 编辑栏未显示

    我正在运行 Plone 4 1 4 当我尝试编辑用于显示tinyMCE 编辑器的文本区域时 我得到的只是一个列出 有效元素 字典的对话框 我安装了 kupu 编辑器并且工作正常 但我更喜欢tinyMCE 有人遇到过这个问题吗 任何帮助将不胜
  • 如何反序列化包含不同类型对象的json数组

    这是一个 json 片段 其中包含一个数组 图标 其中可以包含两种不同类型的对象 应用程序和文件夹 icons application displayName Facebook bundleId com facebook com folde
  • npm 安装错误 - 无法获取本地颁发者证书

    我正在得到一个unable to get local issuer certificate执行 npm install 时出错 typings ERR message Unable to read typings for es6 shim
  • 向内存中的特定地址/位置显式分配或访问值?

    我的确切问题是 其中有任何规定c and c 将值显式分配给特定地址例如假设我想存储20 at 0x1846010内存中的地址 我还想使用同一地址访问一个值 0x1846010 可能很容易 但我真的很困惑如果可以的话如何做到这一点 任何人都
  • JSF f:ajax 不会立即渲染

    我有这样的输入文本
  • VS code,julia linter 不起作用(在 Mac 上)

    在向自己保证 Julia 已启用并且 linter 也已启用 在 VS Code 设置中 Julia Lint Run 后 我在 xxx jl 脚本上得到语法高亮显示 但根本没有 linting 我在最新的 vs code 最新的朱莉娅 1
  • C 中的正则表达式:示例?

    我正在寻找一些关于如何在 ANSI C 中使用正则表达式的简单示例和最佳实践 man regex h并没有提供那么多帮助 正则表达式实际上不是 ANSI C 的一部分 听起来您可能正在谈论 POSIX 正则表达式库 它随大多数 所有 nix
  • Visual Studio 包构建和私有 bin 路径中的 DLL

    我正在使用 MEF 来做一种粗略的插件架构 这运作良好 但是 当我使用 Visual Studio 包 发布构建任务 我通过 NAnt MSbuild 调用 进行部署时 我未引用的插件程序集未包含在包中 因此未部署 有没有办法告诉 VS M
  • 使用 NetBeans 从 java 项目制作可执行文件 [重复]

    这个问题在这里已经有答案了 我在 NetBeans 中创建了一个 java 项目 现在我想用它制作一个可执行文件 该文件可以在安装了 JDK 或 JRE 但没有安装 NetBeans 或任何其他 Java IDE 的其他计算机上执行 运行
  • android hellomap 示例给出异常

    06 14 22 13 33 992 ERROR AndroidRuntime 331 Uncaught handler thread main exiting due to uncaught exception 06 14 22 13 3
  • JavaFXPorts(Gluon 插件) 在 Android 上保存文件

    我在使用 JavaFxPorts 在 Android 上保存文件时遇到问题 我找到了那个链接here 但这对我不起作用 它没有找到接口 我无法使用它 我的目标是使用 JavaFxports 在 Android 上保存文件 Thanks 如果
  • 如何根据 Combobox 的值更改 DataGridView 单元格颜色?

    我有一个 datagridview 如下 我想 当表单加载时 如果Gender列的值为Male 列对应的颜色单元格Name将会是白色的 当 if 改变列的值时Gender 男 女 该列的颜色单元格Name将是深灰色 否则如果更改列的值Gen
  • 如何使用 Java 通过 XSL 转换 XML

    我目前正在使用标准 javax xml transform 库通过 XSL 将 XML 转换为 CSV 我的 XSL 文件很大 大约 950 行 我的 XML 文件也可能很大 它在原型阶段运行良好 只有大约 50 行左右的一小部分 XSL
  • 从 /proc//status 获取 pid 和其他进程信息

    我需要从以下位置获取一些信息 pid 只是一个例子 我知道通过许多其他方式获取它要容易得多 proc PID status 我尝试这样做 include
  • addEventListener 在单击时不触发函数

    这个问题的解决方案可能非常简单 但我需要一些帮助 var x for x in document getElementsByTagName img x addEventListener click openPage false functi
  • SQLite LIKE REGEXP 的替代方案,匹配任何单词的开头

    在 Android 的 SQLite 查询中似乎不可能使用 REGEXP 如果可能的话 请指出我正确的方向 有没有办法使用 LIKE 条件来查询结果中任何单词开头的表达式 例子 Entries 1 最低限度2 铝3 最后一刻 Query m
  • 无法将express-validator与express 3.x一起使用

    我尝试将express validator与express 3 0一起使用 当我调用时它给出了错误 expressValidator require express validator app use expressValidator re
  • SUBSTR 和 INSTR SQL Oracle

    我已经开始在 Oracle 中使用 SUBSTR 和 INSTR 但是当我遇到这个时我感到很困惑 SELECT PHONE SUBSTR PHONE 1 INSTR PHONE 1 FROM DIRECTORY 所以我知道 SUBSTR 截
  • Angular 2 viewchild 不工作 - 无法读取未定义的属性 nativeElement

    我有一个名为 multiselect component 的组件 我访问它的 html 元素之一