【问题标题】:how do i use same templateUrl in two difference component?如何在两个不同的组件中使用相同的 templateUrl?
【发布时间】:2022-01-28 17:14:47
【问题描述】:

我正在做一门在线课程,在其中一部分,老师使用相同的 templateUrl 处理两个不同的组件,一切正常,但是当我尝试做同样的事情时,我的代码没有运行,它说“Property 'is_edit ' 在类型 'ArtistAddComponent' 上不存在"...它没有明显定义,但它是在您编写的第二个中定义的...这让我发疯了。

@Component({    
selector: 'artist-add',
templateUrl: '../views/artist-add.html',
providers: [UserService, ArtistService] 

})

导出类 ArtistAddComponent 实现 OnInit{

public titulo: string;
public artist: any;
public identity:any;
public token: any;
public url: String;
public errorMessage: any;
public alertMessage: any;

constructor(
    private _route: ActivatedRoute,
    private _router: Router,
    private _userService: UserService,
    private _artistService: ArtistService

////////////////////////////////////

@组件({ 选择器:'艺术家编辑', templateUrl: '../views/artist-add.html', 提供者:[UserService, ArtistService]

})

导出类 ArtistEditComponent 实现 OnInit{

public titulo: string;
public artist: any;
public identity:any;
public token: any;
public url: String;
public errorMessage: any;
public alertMessage: any;
public is_edit:any;


constructor(
    private _route: ActivatedRoute,
    private _router: Router,
    private _userService: UserService,
    private _artistService: ArtistService

我已经声明了 this.is_edit=true;但我没有写那部分代码。

/////////////////////////////////////

这是破坏代码的 *ngIf,

<div *ngIf="is_edit">
    <div class="image_for_edit" *ngIf="artist.image != 'null'">
        <img src="{{url + 'get-image-artist/' + artist.image }}" />
    </div>

    <p>
    <label>Suba la imagen del artista</label>
    <input type="file" placeholder="subir imagen..." change="fileChangeEvent($event)" />
    </p>   
</div>

如你所见,两个不同的选择器,因为它们是不同的 component.ts,但我的老师没有问题,所以我需要一个包或其他东西,也许他没有给我们信息?

【问题讨论】:

  • 听起来您正在尝试在模板中使用仅存在于 ArtistEditComponent 上的变量。那是行不通的。
  • 您使用的 HTML 文件应单独查看。这意味着如果artist-add.html 模板引用了is_edit 属性,则它期望使用该模板的所有组件都将is_edit 属性定义为类成员。
  • 这将有助于查看模板中使用的变量,以及两个组件的代码。如果您不想透露逻辑,则无需透露。在我看来,您遇到的错误与在两个组件中使用相同的模板无关。最佳
  • 是的@WillAlexander 我在艺术家添加的模板中使用 *ngIf="is_edit",它抛出了那个错误,但是老师没有在艺术家添加中声明“is_edit”,他只是在艺术家编辑模板中声明它。就好像 Angular 知道他对两个组件都使用了相同的模板,但是我检查了他正在使用的模板并且他显然没有做任何不同的事情......
  • @Luis,不可能。当然你有两个变量,一个声明is_edit:boolean=true,另一个声明is_edit:boolean=false。顺便说一句,我知道这只是一个练习,但是对两个组件使用相同的 .html 这是我能想象的最糟糕的主意,为什么不检查“url”?

标签: angular components


【解决方案1】:

正如你告诉我的,我找不到答案为什么我的老师可以在课程中这样做,我已经按照你的建议为我的 artist-edit.ts 文件创建了一个 HTML 组件,然后我使用了我的选择器作为artist-add.html &lt;artist-edit&gt;&lt;/artist-edit&gt; 中的一个元素,它运行没有问题...现在我可以继续我的课程了,谢谢,

也许我的老师使用的是旧版本的 Angular,他可以这样做。

但我真的很想知道这背后的逻辑,编译器如何让我们知道编译没有问题,为什么他的版本允许他以这种方式使用它以及为什么我不能......如果你知道我将不胜感激。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    相关资源
    最近更新 更多