【问题标题】:How to use an HTML code in another component in NativeScript Angular?如何在 NativeScript Angular 的另一个组件中使用 HTML 代码?
【发布时间】:2021-06-22 19:46:37
【问题描述】:

我正在尝试在其他组件中重复使用我的 HTML 代码。但我找不到这样做的方法。

我编写了一个名为 custom-grid 的组件。 此文件夹包含 2 个文件:custom-grid.component.htmlcustom-grid.component.ts

custome-grid.component.ts 包含以下代码:

import { Component, NgModule, OnInit} from "@angular/core"

@Component({
    selector: "custom-grid",
    templateUrl: "./custom-grid.component.html";
})

export class CustomGridComponent implements OnInit {

    constructor(){
       
    }

    ngOnInit(): void {

    }

}

custom-grid.component.html 包含以下代码:

<div id="myGrid">
  <GridLayout columns="*,*,*" rows="*,*,*,*">
     <!-- some code -->
  </GridLayout>
</div>

现在,我想在几个地方调用这个组件。为此,我在我的 ts 文件上执行此操作:

import { CustomGridComponent } from "../custom-grid/custom-grid.component.ts"

在那些 HTML 文件中,我只是调用:

<StackLayout>
    <Label text="some test"> </Label>
    <custom-grid> </custom-grid>
</StackLayout>

这不起作用并给出以下错误:

CONSOLE ERROR: ERROR {
"originalStack": "Error: Uncaught (in promise): Error: [object Object] is not a valid
 View instance.\nError: [object Object] is not a valid View instance.\n    at new
 ZoneAwareError (file:///app/vendor.js:153110:33)\n    at StackLayout._addView
 (file:///app/vendor.js:118087:19)\n    at StackLayout.addChild 
(file:///app/vendor.js:129052:14)\n    at StackLayout.addChild 
(file:///app/vendor.js:129169:15)\n    at ViewUtil.insertToLayout 
(file:///app/vendor.js:95036:20)\n    at ViewUtil.addToVisualTree 
(file:///app/vendor.js:95017:18)\n    at ViewUtil.insertChild 
(file:///app/vendor.js:94977:18)\n    at EmulatedRenderer.appendChild 
(file:///app/vendor.js:95314:23)\n    at EmulatedRenderer.appendChild 
(file:///app/vendor.js:95575:15)\n    at nativeAppendChild 
(file:///app/vendor.js:51151:18)\n    at nativeAppendOrInsertBefore 
(file:///app/vendor.js:51162:9)\n    at appendChild (file:///app/vendor.js:51252:13)\n  
  at ɵɵelementStart (file: 
node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:14562:0)\n    at Module.<…>

如果我做错了,请纠正我,否则任何其他可能的方法都可以正常工作。 任何形式的帮助都会很有用。提前谢谢你:)

PS:我也试过这个 Unable to use ng-include in angular 5

【问题讨论】:

    标签: angular nativescript nativescript-angular


    【解决方案1】:

    您确定您在 app.module 中正确声明了该组件吗? 无论如何-

    1. 您不必将它导入到要在 HTML 中实现的 TS 中。
    2. 这种方式将重用整个组件,而不仅仅是 HTML。
    3. 如果您只想要 HTML,您可以在第二个组件的选择器中提供其路径,如下所示:

    `

    @Component({
    selector: "second-component",
        templateUrl: "../..{the right path}/custom-grid.component.html";
    })
    
    export class SecondComponent {
        constructor(){
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-30
      相关资源
      最近更新 更多