html - Angular 多次实例化组件

标签 html css angular

我正在使用 angular 6,我无法多次实例化一个组件,我试图在堆栈溢出上看到类似的问题,但我没有找到答案

这里是html-div-component.html

<div [style.opacity]="opacity" class='div-component' [style.margin- top.px]="marginTop">    

html-div.component.ts

@Component({
   selector: 'app-html-div',
   templateUrl: './html-div.component.html',
   styleUrls: ['./html-div.component.css']
})     
export class HtmlDivComponent implements OnInit {

  @Input() name;

  @ViewChildren('div-component') elements: QueryList<HtmlDivComponent>;

  ...

  constructor() { }

  ngOnInit() {
    console.log('initializing');
    window.addEventListener('scroll', this.scrollHandler, true);
    window.onload = (event) => {
    ...
  };

 }
 ...
}

这里是父组件.html

<app-html-div id="get-started-div" name="blue">
<div class="charat-list default-panel mui-panel">
  <h2 class="forstyle-h2">/h2>
  <p>
    <input type="button" value="1">
  </p>
  <p>
    <input type="button" value="2">
  </p>
</div>
</app-html-div>
<app-html-div name="green">
<div class="charat-list default-panel mui-panel">
  <h2 class="forstyle-h2"></h2>
  <p>
    <input type="button" value="1">
  </p>
  <p>
    <input type="button" value="2">
  </p>
</div>

在我的日志控制台中我看到了这个

initializing

谢谢你的帮助

最佳答案

正如在评论中所讨论的,ngOnInit 中的控制台日志将在浏览器开发人员工具中被控制台控制台使用的次数与所使用的组件一样多

代码示例 - https://stackblitz.com/edit/angular-qwae9v?file=src/app/app.component.html
https://stackblitz.com/edit/angular-dvaleu?file=src/app/hello.component.ts

在您的情况下,这不是应用程序的问题,但浏览器开发人员工具旨在将重复的控制台消息堆叠到一个并显示重复的次数

检查此链接以供引用 - https://developers.google.com/web/tools/chrome-devtools/console/根据 Chrome 文档

消息堆叠
如果消息连续重复,而不是在新行上打印出消息的每个实例,控制台会“堆叠”消息并在左边距中显示一个数字。该数字表示消息重复了多少次。

只是为了测试和理解,试试这个简单的例子

for (i = 0; i < 4; i++) { 
    alert("test")
    console.log("test")
}

//ouput you will see in console as 3 test, you will see three alert windows

关于html - Angular 多次实例化组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52469106/

相关文章:

jquery - 文本输入字段的页面溢出

html - 为 HTML 微型网站禁用 CSS

javascript - 使用javascript根据从数据库中获取的值更改输入字段边框颜色

javascript - typescript : Property 'data' dose not exist on type HTMLElement

typescript - 如何在 angular2 中将 ag-grid 与 Observable 一起使用?

javascript - 基于单选选择的模态图像作为数组索引

javascript - 控制css文件的加载顺序

css - 带有下拉菜单的图像按钮

javascript - 指令在应用程序中不起作用

JavaScript .change() 错误。不自动更改 Chrome 中的选择框