【问题标题】:Page stops loading after using component selector in another html file Angular 5在另一个html文件Angular 5中使用组件选择器后页面停止加载
【发布时间】:2019-02-28 22:30:13
【问题描述】:

我正在尝试在注册表单上添加图片上传并创建一个上传组件,我将在其中放置我的上传按钮 html。

我在 app/shared/forms/image-upload/upload 中创建了组件。

这里是upload.component.ts文件代码:

import { Component, EventEmitter, Input, Output } from '@angular/core';
import { FormArray, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { HttpErrorResponse } from '@angular/common/http';

import { UploadEvent, UploadFile } from '../../../file-drop';
import { SortingService } from '../../../services/sorting.service';
import { FileService } from '../../../../api';
import { File } from '../../../../api/models';

import { NotificationsService } from '../../../../shared/notifications';
import { forEach } from '@angular/router/src/utils/collection';

@Component({
  selector: 'repo-upload',
  templateUrl: './upload.component.html',
  styleUrls: ['./upload.component.scss']
})
export class UploadComponent{

  @Input() parentFormGroup: FormGroup;
  @Input() file: File;
  @Output()
  public onImageChange: EventEmitter<File> = new EventEmitter<File>();

  public imageList: UploadFile[];
  private imageMimeTypes: string[] = ['image/jpeg', 'image/png', 'image/gif'];


  constructor(private formBuilder: FormBuilder, private sortingService: SortingService, private fileService: FileService, private notificationsService: NotificationsService) {
    this.imageList = this.sortingService.list;

  }

  ngOnInit() {
      this.parentFormGroup.addControl('images', this.formBuilder.array([], Validators.required));
  }
  /**
   * add image to the file uploader
   *
   * @param event
   */
  handleImageAdd(event: UploadEvent) {
    for (let i = 0; i < event.files.length; i++) {
      let formControl = new FormControl();
      this.images.push(formControl);

      let uploadFile = event.files[i];
      let error: any;
      if (!this.imageMimeTypes.includes(uploadFile.file.type)) {
        error = error || {};
        error.mimes = true;
      }

      // Size is given in bytes
      if (uploadFile.file.size > 10000000) {
        error = error || {};
        error.max = true
      }

      if (error) {
        formControl.setErrors(error);
      }
    }

    this.checkFormValidity();
    this.sortingService.addAll(event.files);

    this.handleImageSave(event);
  }

  handleImageSave(event) {
    //iterate through each uploaded image, save it and remove it from the file dropper
    this.imageList.forEach((uploadFile, index, imageList) => {
      let fileFormData = new FormData();
      fileFormData.append('file', uploadFile.file);

      this.fileService.save(fileFormData)
        .subscribe(
        (file) => {
          this.notificationsService.success('Image saved successfully!');
          imageList.splice(index);
          this.onImageChange.emit(file);
        },
        (err: HttpErrorResponse) => {
          if (err.status === 422) {
            console.log(err);
          }
        }
        );
    });
  }

  removeImage(index: number) {
    this.sortingService.remove(index);
    this.images.removeAt(index);
    this.checkFormValidity();
  }

  private checkFormValidity() {
    if (this.images.length > 0) {
      this.images.setValidators([]);
    } else {
      this.images.setValidators([Validators.required]);
    }
    this.images.updateValueAndValidity();
  }

  get images() {
    return this.parentFormGroup.get('images') as FormArray;
  }
}

现在的问题是,当我在 signup-form.component.html 文件中使用 &lt;repo-upload&gt;&lt;/repo-upload&gt; 时,页面不会显示任何内容。

当我查看页面的控制台时,我收到了一个错误。见截图:

谁能帮我解决这个问题。我从前 1 天开始尝试修复它。

编辑:

我忘了在 app.module.ts 文件中添加这个组件。在 app.module.ts 文件中添加它后,我收到错误:

Uncaught Error: Type UploadComponent is part of the declarations of 2 modules: SharedModule and AppModule! Please consider moving UploadComponent to a higher module that imports SharedModule and AppModule. You can also create a new NgModule that exports and includes UploadComponent then import that NgModule in SharedModule and AppModule.

编辑:

这是我的 app.module.ts 文件:

import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { RECAPTCHA_SETTINGS, RecaptchaModule, RecaptchaSettings } from 'ng-recaptcha';
import { RecaptchaFormsModule } from 'ng-recaptcha/forms';
import { AgmCoreModule } from '@agm/core';
import { FroalaEditorModule, FroalaViewModule } from 'angular-froala-wysiwyg';
import { Ng4LoadingSpinnerModule } from 'ng4-loading-spinner';
import { DeviceDetectorModule } from 'ngx-device-detector';

import { environment } from '../environments/environment';
import { ApiModule, ProfileService, PropertyService } from './api';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AuthModule } from './auth';
import { DummyComponent } from './dummy.component';
import { InterceptorsModule } from './interceptors';
import { LoginComponent } from './login/login.component';
import { NavbarComponent } from './navbar/navbar.component';
import { NotFoundComponent } from './not-found/not-found.component';
import { ProfileComponent } from './profile/profile.component';
import { SharedModule } from './shared';
import { UserModule } from './user';
import { SignupFormComponent } from './user/signup-form/signup-form.component';
import { PropertySearchFormComponent } from './property/property-search-form/property-search-form.component';
import { PropertyViewComponent } from './property/property-view/property-view.component';
import { SearchComponent } from './search/search.component';
import { SearchResultlistComponent } from './search/search-resultlist/search-resultlist.component';
import { SearchResultComponent } from './search/search-result/search-result.component';
import { ProfileSearchFormComponent } from './profile/profile-search-form/profile-search-form.component';
import { ProfileViewComponent } from './profile/profile-view/profile-view.component';
import { ProfileEditComponent } from './profile/profile-edit/profile-edit.component';
import { ErrorComponent } from './error/error.component';
import { InquiriesComponent } from './inquiries/inquiries.component';
import { InquiryItemComponent } from './inquiries/inquiry-item/inquiry-item.component';
import { PropertyEditComponent } from './property/property-edit/property-edit.component';
import { PropertyComponent } from './property/property.component';
import { InquiryItemFormComponent } from './inquiries/inquiry-item-form/inquiry-item-form.component';
import { AccountComponent } from './user/account/account.component';
import { AccountViewComponent } from './user/account/account-view/account-view.component';
import { AccountEditComponent } from './user/account/account-edit/account-edit.component';
import { PasswordResetComponent } from './user/password-reset/password-reset.component';
import { PasswordResetSendComponent } from './user/password-reset/password-reset-send/password-reset-send.component';
import { PasswordResetSubmitComponent } from './user/password-reset/password-reset-submit/password-reset-submit.component';
import { UserAuthentificationComponent } from './user/user-authentification/user-authentification.component';
import { GlobalNotificationsDirective } from './global-notifications/global-notifications.directive';
import { SearchInfoWindowComponent } from './search/search-info/search-info-window/search-info-window.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { BsDropdownModule } from 'ngx-bootstrap/dropdown';
import { NgxIntlTelInputModule } from 'ngx-intl-tel-input';
import { TenantDetailComponent } from './profile/tenant-detail/tenant-detail.component';

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    NavbarComponent,
    SignupFormComponent,
    DummyComponent,
    PropertyComponent,
    PropertySearchFormComponent,
    PropertyViewComponent,
    SearchComponent,
    SearchResultlistComponent,
    SearchResultComponent,
    ProfileSearchFormComponent,
    NotFoundComponent,
    ProfileComponent,
    ProfileViewComponent,
    ProfileEditComponent,
    ErrorComponent,
    InquiriesComponent,
    InquiryItemComponent,
    PropertyEditComponent,
    InquiryItemFormComponent,
    AccountComponent,
    AccountViewComponent,
    AccountEditComponent,
    PasswordResetComponent,
    PasswordResetSendComponent,
    PasswordResetSubmitComponent,
    UserAuthentificationComponent,
    GlobalNotificationsDirective,
    SearchInfoWindowComponent,
    DashboardComponent,
    TenantDetailComponent,
  ],
  imports: [
    NgbModule.forRoot(),
    AgmCoreModule.forRoot({
      apiKey: environment.googleMapApiKey,
      libraries: ["places"]
    }),
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    RecaptchaModule.forRoot(),
    RecaptchaFormsModule,
    AppRoutingModule,
    ApiModule.forRoot(),
    AuthModule.forRoot(),
    InterceptorsModule,
    SharedModule,
    UserModule,
    [FroalaEditorModule.forRoot(), FroalaViewModule.forRoot()],
    [Ng4LoadingSpinnerModule.forRoot()],
    DeviceDetectorModule.forRoot(),
    BsDropdownModule.forRoot(),
    NgxIntlTelInputModule
  ],
  providers: [
    {
      provide: RECAPTCHA_SETTINGS,
      useValue: { siteKey: environment.recaptchaSiteKey } as RecaptchaSettings
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

【问题讨论】:

  • 确保您在 app.module.ts 或其他模块的声明中添加了“UploadComponent”。
  • 是的,在这里发布后,我查看了我的 app.module.ts,但我忘了在其中添加这个组件。但是在添加它之后,我得到了另一个错误。我在上面更新了。你能看看吗。
  • 您不能在多个模块中添加相同组件、管道、指令等的声明。即您的应用程序中必须只有一个组件声明。因此,根据您的应用程序,将其添加到 app.module.ts 或 shared.module.ts
  • 是的,我同意,但只添加 shared.module.ts 我得到的'repo-upload' is not a known error.
  • app.module.ts文件中已经导入shared.module.ts文件

标签: angular components angular5 image-upload


【解决方案1】:

根据上述数据,您似乎没有在模块中输入您的组件

1 将组件条目添加到 shared.module.ts(如果有),否则条目应该在 app.module.ts 中

2 不要忘记在声明中输入:[ addComponentname ] Array

3 尝试在模块 add.module.ts 和 shared.module.ts 中添加组件条目

【讨论】:

  • 感谢您的回复。我在shared.module.ts 文件中添加了它。早些时候,我在添加 app.module.ts 后没有添加 app.module.ts,我收到了在我上面的问题中更新的错误。
  • 你能把3个选项检查一遍吗
  • 你能发布你的 app.module.ts
  • shared.module.ts 中,代码用作import { UploadComponent } from './forms/image-upload/upload/upload.component';UploadComponent 被添加到declarations 数组中。在 app.module.ts 我添加了import { UploadComponent } from './shared/forms/image-upload/upload/upload.component'; 并得到了我在编辑部分更新的错误
  • 我用 app.module.ts 文件更新了我的帖子。看看吧。
猜你喜欢
  • 2014-04-07
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
  • 2018-11-16
  • 1970-01-01
  • 2013-06-08
  • 2017-05-09
相关资源
最近更新 更多