You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 18中如何使用依赖NgModule的第三方图像绘制库?

在Angular 18独立组件中使用ngx-image-drawing-zone库

我尝试使用图像绘制库ngx-image-drawing-zone,该库文档要求通过NgModule导入ImageDrawingModule,但我用的是Angular 18,项目里没有app.module.ts这类NgModule文件,完全是独立组件结构。请问该怎么在这种无NgModule的环境下使用这个库?

以下是我的组件代码:

组件TS代码

import { Component, OnInit } from '@angular/core';
import { NavigationComponent } from '../navigation/navigation.component';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { Category } from 'app/interfaces/category';
import { OfferService } from 'services/offer-service';
import { DataService } from 'services/data-service';
import { ImageDrawingComponent } from 'ngx-image-drawing';

@Component({
  selector: "create-offer",
  standalone: true,
  imports: [ReactiveFormsModule, NavigationComponent, ImageDrawingComponent],
  templateUrl: "./create-offer.component.html",
})
export class CreateOfferComponent implements OnInit {
  createOfferForm: FormGroup
  categories: Category[] = []
  selectedCategories: string[] = []
  errors: Error | undefined;

  constructor(private formBuilder: FormBuilder,
    private dataService: DataService,
    private router: Router,
    private offerService: OfferService
  ) { this.createOfferForm = new FormGroup({}) }

  ngOnInit(): void {
    this.createOfferForm = this.formBuilder.group({
      title: ['', Validators.required],
      description: ['', Validators.required],
      price: ['', Validators.required],
      categories: ['', Validators.required]
    })

    this.dataService.getCategories().subscribe(
      (data: Category[]) => {
        this.categories = data
      }
    )

  }

  findInvalidControls() {
    const invalid = [];
    const controls = this.createOfferForm.controls;
    for (const name in controls) {
      if (controls[name].invalid) {
        invalid.push(name);
      }
    }
    return invalid;
  }

  onSubmit() {
    console.log('create-offer form submit')
    console.log(this.findInvalidControls())
    if (this.createOfferForm.invalid) return

    const formData = new FormData()
    formData.append('title', this.createOfferForm.get('title')?.value)
    formData.append('description', this.createOfferForm.get('description')?.value)
    formData.append('price', this.createOfferForm.get('price')?.value)
    formData.append('categories', JSON.stringify(this.selectedCategories))
    formData.append('status', "PENDING")
    formData.append('timeCreated', (Date.now()).toString())

    this.offerService.createOffer(formData).subscribe({
      next: (value) => {
        if (value) {
          this.router.navigateByUrl("/offers")
        }
      },
      error: (err) => {
        console.log(err)
      }
    })
  }

  onChange(value: string) {
    if (this.selectedCategories.includes(value)) {
      const index = this.selectedCategories.indexOf(value, 0);
      if (index > -1) {
        this.selectedCategories.splice(index, 1);
      }
    } else {
      this.selectedCategories.push(value)
    }
  }
}

组件HTML代码

<navigation class="navigation"></navigation>
<div class="container mx-auto py-2 mt-3">
  <form (ngSubmit)="onSubmit()" [formGroup]="createOfferForm"
    class="max-w-fit mx-auto bg-white shadow-lg rounded px-4 py-4 flex flex-col">
    <div class="w-full flex flex-col md:flex-row">
      <div class="w-full md:w-1/2 p-8">
        <h2 class="mb-4 text-blue-500 font-semibold">Create Offer Form</h2>

        <div class="mb-4">
          <label for="title" class="block mb-2">Title:</label>
          <input type="text" id="title" formControlName="title" required
            class="block w-full px-4 py-2 rounded border border-gray-300 focus:outline-none focus:border-blue-500">
        </div>

        <div class="mb-4">
          <label for="description" class="block mb-2">Description:</label>
          <input type="text" id="description" formControlName="description" required
            class="block w-full px-4 py-2 rounded border border-gray-300 focus:outline-none focus:border-blue-500">
        </div>

        <div class="mb-4">
          <label for="price" class="block mb-2">Price:</label>
          <input type="text" id="price" formControlName="price" required
            class="block w-full px-4 py-2 rounded border border-gray-300 focus:outline-none focus:border-blue-500">
        </div>
      </div>

      <div class="w-full md:w-1/2 p-4">
        <div class="mb-4 flex flex-col justify-between ">
          <label class="mb-2">Categories:</label>
          <div class="ml-2">
            @for(category of categories; track category){
            <label class="block mb-2">
              <input type="checkbox" (change)="onChange(category.category)" [value]="category.category"
                formControlName="categories" required>
              <span>{{ category.category }}</span>
            </label>
            }
          </div>
        </div>
      </div>
    </div>

    <div class="w-full md:w-1/2 px-8">
      <button type="submit"
        class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 focus:outline-none focus:bg-blue-600">Submit</button>
    </div>

  </form>

  <image-drawing [src]="imageUrl" outputMimeType="'image/jpeg'" outputQuality="0.8" (save)="save($event)"
    (cancel)="cancel()">
  </image-drawing>
</div>

解决方案

在Angular 18的独立组件体系中,无需依赖NgModule,直接通过以下步骤调整即可使用该库:

  1. 修正组件导入路径
    当前代码导入的是ngx-image-drawing,但实际使用的库是ngx-image-drawing-zone,需修改导入语句:

    import { ImageDrawingComponent } from 'ngx-image-drawing-zone';
    
  2. 补充模板依赖的变量和方法
    模板中用到了imageUrl变量、save($event)和cancel()方法,但组件类中未定义,需补充:

    // 定义初始图片URL,替换为你的实际图片地址
    imageUrl: string = 'https://your-image-url.com/image.jpg';
    
    // 实现保存回调
    save(imageData: string) {
      console.log('保存的图像数据:', imageData);
      // 可在此添加上传图像到服务器的逻辑
    }
    
    // 实现取消回调
    cancel() {
      console.log('取消绘制');
    }
    
  3. 修正模板属性绑定
    模板中outputMimeType的单引号多余,直接传字符串值即可:

    <image-drawing [src]="imageUrl" outputMimeType="image/jpeg" outputQuality="0.8" (save)="save($event)" (cancel)="cancel()">
    </image-drawing>
    
  4. 确认库组件支持独立模式
    该库基于Angular 14+开发,组件默认是standalone: true,直接添加到组件的imports数组即可生效,无需额外配置。

完成以上调整后,组件就能正常加载并使用图像绘制功能了。

内容的提问来源于stack exchange,提问作者strandom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 16:29:51