简体   繁体   English

如何在angular 4中创建组件定义类的实例?

[英]How to create instance of component definition class in angular 4?

I am new in angular 4 and I am learning it day by day using tutorials but I am not understanding after a lot of research that how to create an instance of component class. 我是angular 4的新手,并且每天都在使用教程学习它,但是经过大量研究后,我不了解如何创建组件类的实例。

This is the sample code that I am following 这是我关注的示例代码

export class UserItemComponent implements OnInit {
 name: string; // <-- added name property

   constructor() {
    this.name = 'Felipe'; // set the name
   }

   ngOnInit() {
   }

}

I am rendering this component /user-item.component.html like this 我正在像这样渲染此组件/user-item.component.html

<p>
 Hello {{ name }}
</p>

and then /app.component.html file 然后是/app.component.html文件

<app-user-item></app-user-item>

It displays the name "Felipe" correctly but I am not understanding that how It is working. 它正确显示名称“ Felipe”,但我不了解它的工作方式。 I know about constructor is calling when the instance is creating but I don't know which one is the instance in the below? 我知道在实例创建时构造函数正在调用,但是我不知道下面的实例是哪个?

<app-user-item></app-user-item>
{{ name }}

I know oop concepts very well but in angular I am still confuse about its terms and flow. 我非常了解oop概念,但从角度上讲,我仍然对其术语和流程感到困惑。 Any help would be highly appreciated.Thanks. 任何帮助将不胜感激。谢谢。

@Antikhippe when your app get load, it rend a view which is app.component.html. @Antikhippe当您的应用加载时,它会显示一个视图,即app.component.html。 In your case that View is rendering another View "" which has this piece of code " 在您的情况下,View正在呈现另一个具有此代码段“

Hello {{ name }} 您好{{name}}

" when angular see the {{ ...}} it knows that you are referencing a property that is available in the component most of the time the .ts. That concept is what angular call "Data binding". you can create a class in a separate file (.ts) within the component folder , import the class in the component class and instantiate an object of the class just like in java : "this.model = new SubjectInfo();" "this" has the same meaning like in all OOP it reference the property of the component class. "SubjectInfo" is the class that I imported in my component class. I hope that help. “当有角度时,请参阅{{...}},它知道您大部分时间都是在.ts中引用组件中可用的属性。该概念就是有角度的“数据绑定”。您可以创建一个类在component文件夹中的单独文件(.ts)中,将组件类导入该类并实例化该类的对象,就像在java中一样:“ this.model = new SubjectInfo();”“ this”具有相同的含义就像在所有OOP中一样,它引用了组件类的属性。“ SubjectInfo”是我在组件类中导入的类,希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM